首页 > 解决方案 > 我可以使用整数变量来定义数组长度吗?

问题描述

我可以使用变量来定义数组的大小吗?

int test = 12;
int testarr[test];

这行得通吗,我不想在初始化后更改数组的大小。'的int test值在编译时是未知的。

标签: carraysvariable-length-array

解决方案


从 C99 开始,它是允许的,但仅适用于自动变量。

这是非法的:

int test = 12;
int testarr[test];   // illegal - static storage variable

int foo(void) 
{
    int test = 12;
    static int testarr[test];   // illegal - static storage variable
}

唯一有效的形式是:

int foo(void) 
{
    int test = 12;
    int testarr[test];   // legal - automatic storage variable
}

推荐阅读