使用c语言在运行时确定大小的数组?

使用c语言在运行时确定大小的数组?,c,arrays,variables,runtime,user-input,C,Arrays,Variables,Runtime,User Input,我想创建一个数组,其大小将在运行时确定,即用户输入 我试着这样做: printf("enter the size of array \n"); scanf("%d",&n); int a[n]; 但这导致了一个错误 如何设置这样的数组大小?除非使用C99(或更新版本),否则需要手动分配内存,例如使用calloc() 您需要包括stdio.h,声明n,并将代码放入函数中。除此之外,你所做的应该是有效的 #include <stdio.h> int main(void)

我想创建一个数组,其大小将在运行时确定,即用户输入

我试着这样做:

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

scanf("%d",&n);

int a[n];
但这导致了一个错误

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

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


您需要包括
stdio.h
,声明
n
,并将代码放入函数中。除此之外,你所做的应该是有效的

#include <stdio.h>

int main(void)
{
        int n;
        printf("enter the size of array \n");
        scanf("%d",&n);
        int a[n];
}
#包括
内部主(空)
{
int n;
printf(“输入数组的大小\n”);
scanf(“%d”和“&n”);
int a[n];
}

您使用的编译器是什么?它显示了什么错误?如果OP有一个兼容c99的编译器,为什么?“除非您使用的是c99”。C11没有删除可变长度数组。@ThiefMaster也在挑剔,为什么
calloc
而不是
malloc
?@CharlesBailey别忘了
calloc
malloc
慢,因为归零的开销。@SeçkinSavaşıç:你为什么要把它指向我?把你的编译器切换到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 
#include <stdio.h>

int main(void)
{
        int n;
        printf("enter the size of array \n");
        scanf("%d",&n);
        int a[n];
}