c - 变量数组声明

标签 c arrays

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

相关文章:

php - 更新以前的 session 数组 Laravel

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c - 在 linux 上,使用 ZLIB 的 compress() 和 uncompress() 函数,它有时会返回 Z_BUFFER_ERROR

c++ - 获取地址信息 : in what way is AI_PASSIVE ignored if the nodename is specified?

c - 算法问题——判断数组是否已经分区(即快速排序的一步)

c++ - ESP8266 尝试从字节数组读取 float 时出现异常

c - 在c中分配给struct中的数组

C语言 : I want to see if a value of a[] is less than all the values of b[]

c - 在 MS Windows 系统上用 C 语言打开/dev/null 之类的文件?

c - 如何连接两个字符串,其中源字符串应附加在目标字符串之前?