我是 C 程序员并且正在使用
gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3
下面的静态数组正在工作
int i=10;
int a[i];
它工作正常,但根据我的说法,它应该在这种类型的数组声明中给出错误, 任何人都可以告诉我这是什么行为?
最佳答案
你是对的 - 根据 C99 standard , section 6.7.5.2, part 2, static arrays cannot be declared with variable length:
Only an ordinary identifier (as defined in 6.2.3) with both block scope or function prototype scope and no linkage shall have a variably modified type. If an identifier is declared to be an object with
static
storage duration, it shall not have a variable length array type. (emphasis added)
#include <stdio.h>
int i = 5;
int a[i]; // <<== ERROR - this does not compile
对于非静态数组(例如自动存储区中的数组,也称为“栈”),这是允许的。此外,您甚至可以从函数外部传递 i
:
void test(int i) {
int a[i]; // C99 allows this; gcc allows this in c90 as well.
}
关于c - 为什么静态数组工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732668/