第1个回答 2010-10-30
在所需内存大小已知的时候也可以用数组申请,malloc函数用在其大小在运行时才确定的情况,此时就无法用数组来做了
堆是用来存放数据的,使用堆为了让cpu可以找到相应的数据,如果自由分配,cpu无法确定这是程序还是数据,是什么类型的数据
第2个回答 2010-10-30
malloc的意思你没有了解呀。
Allocates memory blocks.这是最正统的解释,msdn上的。只是用来分派空间的。没有涉及什么堆和数组之类的东西。
void *malloc( size_t size );
Parameters
size
Bytes to allocate
Libraries
All versions of the C run-time libraries.
Return Values
malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.
Remarks
The malloc function allocates a memory block of at least size bytes. The block may be larger than size bytes because of space required for alignment and maintenance information.
第3个回答 推荐于2017-09-08
1、这个涉及两个存储区域,堆和栈,用malloc申请的空间在堆上,char a[10]这个是在栈上。堆和栈最重要一个区别是,栈是系统管理的的,他负责回收和释放,所以有个概念叫作用域,变量的作用域一结束,栈就回收变量的资源。但是堆是程序员管理的,程序员不释放,除非进程结束,这个空间就一直在那,就有了一定灵活性。
2、当无法知道内存具体位置的时候,想要绑定真正的内存空间,就需要用到动态的分配内存,即malloc函数。
malloc函数原型:extern void *malloc(unsigned int num_bytes);
头文件:#include <stdlib.h>
功能:分配长度为num_bytes字节的内存块
返回值:如果分配成功则返回指向被分配内存的指针(此存储区中的初始值不确定),否则返回空指针NULL。当内存不再使用时,应使用free()函数将内存块释放。函数返回的指针一定要适当对齐,使其可以用于任何数据对象。
说明:关于该函数的原型,在以前malloc返回的是char型指针,新的ANSIC标准规定,该函数返回为void型指针,因此必要时要进行类型转换。