请在C中考虑这些代码:
int n;
scanf("\n%d ",&n);
int arr[n];
和这个。
int n;
scanf("\n%d ",&n);
int *p = (int *)malloc(n*sizeof(int));
为什么我们首先需要为此分配动态内存?并且在运行时创建数组时,第一个代码不是动态内存分配吗?
我何时应该使用malloc()?
[int arr[n];
allocates memory on the stack。是automatically allocated and then deallocated at the end of the block。无法从函数安全地返回指向堆栈存储器的指针。
考虑这个。
#include <stdio.h>
char *make_array() {
int n;
scanf("%d",&n);
// Memory for `arr` is allocated on the stack.
char arr[n];
// And then deallocated when the function exits.
// A good compiler and editor will warn you if you try
// to return it.
return arr;
}
int main() {
// This pointer is to memory which has already been freed. Other things
// will overwrite it.
char *arr = make_array();
arr[0] = 'c';
arr[1] = '\0';
// This could be the letter c, but it's probably gibberish.
puts(arr);
}
如果需要超出当前函数寿命的内存,则需要使用malloc
在堆上分配它并自己进行管理。
请确保您了解:
当“函数调用函数”时,它们的局部变量存储在称为“堆栈”的内存区域中,之所以这样命名,是因为它的工作方式类似于下层LIFO堆栈。输入功能后,堆栈会增加。函数返回时,它会缩小。而且,如果函数递归调用itself,,则不会造成混淆,因为每个实例在堆栈上都有其自己的区域。
malloc()
根据请求从另一个称为“堆”的区域分配内存,之所以如此命名是因为它没有特定的内置组织。使用“指针” 引用这些内存区域,这些指针的变量值被理解为内存地址。“ C语言方便地允许您在使用指针时使用”数组符号“,就像在堆栈上分配的局部变量一样。
int n;
scanf("\n%d ",&n);
int arr[n];
int n;
scanf("\n%d ",&n);
int arr[n];