rlh*_*lh2 0 c variable-length-array
什么时候用 calloc 实例化可变长度数组比用 C 中的“普通”数组声明更好?
考虑“数组声明”方法:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
int x[n];
for(int i = 1; i < n; i++){
x[i] = i;
printf("%i", x[i]);
printf("\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
与 calloc 方法相比:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
int * x = (int*) calloc(n, sizeof(int));
for(int i = 1; i < n; i++){
x[i] = i;
printf("%i", x[i]);
printf("\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您应该始终使用其中之一吗?其中一个比另一个更快(例如堆栈分配与堆分配的 bc)吗?其中一个比另一个风险大吗?
int x[n];
Run Code Online (Sandbox Code Playgroud)
包括 VLA 在内的自动存储持续时间对象(通过大多数现代实现)在堆栈上分配。如果将较大的对象分配在堆栈上,则会出现一些问题(三个最重要的问题):