考虑下面的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/

10-12 14:37
查看更多