C语言“堆”申请为什么用malloc函数,用数组不行吗?

heap:
需要程序员自己申请,并指明大小,在c中malloc函数
如p1 = (char *)malloc(10);
问: 用数组申请一个堆不行吗, char a[10], *P1 ; P1 = a; 向这样不也得到10字节空间么?
“堆”是不是很多连续的空间块 ,由指针相互链接在一起?
另外,申请堆一般用来做什么呢? 把程序自由在RAM里分配不也一样么, 单片机。

这个涉及两个存储区域,堆和栈,你用malloc申请的空间在堆上,char a[10]这个是在栈上。

堆和栈最重要一个区别是,栈是系统管理的的,他负责回收和释放,所以有个概念叫作用域,变量的作用域一结束,栈就回收变量的资源。但是堆是程序员管理的,你不释放,除非进程结束,这个空间就一直在那,就有了一定灵活性。
回答了申请堆的作用。

堆在实现的时候确实是在底层是链表的形式没错,栈是连续的空间。
温馨提示:内容为网友见解,仅供参考
第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型指针,因此必要时要进行类型转换。
相似回答