考虑下面的 C 代码:
#include<stdio.h>
int main()
{int n,i;
scanf("%d",&n);
int a[n]; //Why doesn't compiler give an error here?
}
当编译器最初不知道时,如何声明数组?
最佳答案
当数组的确切大小直到编译时才知道时,您需要使用动态内存分配。在C标准库中,有动态内存分配的函数:malloc、realloc、calloc和free。
这些函数可以在 <stdlib.h>
中找到头文件。
如果你想创建一个数组,你可以这样做:
int array[10];
在动态内存分配中,您会执行以下操作:
int *array = malloc(10 * sizeof(int));
您的情况是:
int *array = malloc(n * sizeof(int));
如果您分配了内存位置,请不要忘记释放:
if(array != NULL)
free(array);
内存分配是一个复杂的主题,我建议您搜索该主题,因为我的答案很简单。您可以从以下链接开始:
https://www.programiz.com/c-programming/c-dynamic-memory-allocation
关于c - 变量数组声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47004684/