变量数组声明

考虑下面的C代码:

#include int main() {int n,i; scanf("%d",&n); int a[n]; //Why doesn't compiler give an error here? } 

当编译器最初不知道时,如何声明数组?

如果在编译时直到数组的确切大小未知,则需要使用动态内存分配。 在C标准库中,有动态内存分配函数:malloc,realloc,calloc和free。

这些函数可以在头文件中找到。

如果你想创建一个数组,你可以:

 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