c - 在C语言中,数组的大小在运行时确定?

标签 c arrays variables runtime user-input

我想创建一个数组,其大小在运行时(即用户输入)期间确定。

我尝试这样做:

printf("enter the size of array \n");

scanf("%d",&n);

int a[n];

但这导致了错误。

如何设置这样的数组大小?

最佳答案

除非您使用 C99(或更新版本),否则您需要手动分配内存,例如使用calloc()

int *a = calloc(n, sizeof(int)); // allocate memory for n ints
// here you can use a[i] for any 0 <= i < n
free(a); // release the memory

如果您有符合 C99 标准的编译器,例如GCC 与 --std=c99,您的代码工作正常:

> cat dynarray.c
#include <stdio.h>
int main() {
        printf("enter the size of array \n");
        int n, i;
        scanf("%d",&n);
        int a[n];
        for(i = 0; i < n; i++) a[i] = 1337;
        for(i = 0; i < n; i++) printf("%d ", a[i]);
}
> gcc --std=c99 -o dynarray dynarray.c
> ./dynarray
enter the size of array
2
1337 1337 

关于c - 在C语言中,数组的大小在运行时确定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10861190/

相关文章:

c - RIOT OS - "stdout"用于嵌入式平台

c - 4字节数组转换为float(c)

javascript - 在javascript中对多维数组进行排名

ruby - 二维数组,推到一个数组显示在所有数组中?

c - 确定数组中的最大值

javascript - 将变量从 while 循环内传递到 popupdiv

仅使用整数常量表达式计算 sqrt(SIZE_MAX+1),以适应奇怪的 ABI

c - C 形式定义中的命名空间

swift - 带下划线的变量声明

c - 如何强制程序识别单词并停止