简单回答variable modified array at file scope is not possible。
详细:
让它编译时integral constant expression,因为数组长度必须在编译时指定。
像这样:
#define a 6
#define b 3
或者,遵循 c99 标准。并像 gcc 一样编译。
gcc -Wall -std=c99 test.c -o test.out
这里的问题是提供长度的可变长度数组可能没有被初始化所以你得到这个错误。
简单
static int a =6;
static int b =3;
void any_func()
{
int Hello [a][b]; // no need of initialization no static array means no file scope.
}
现在使用 for 循环或任何循环来填充数组。
更多信息只是一个演示:
#include <stdio.h>
static int a = 6;
int main()
{
int Hello[a]={1,2,3,4,5,6}; // see here initialization of array Hello it's in function
//scope but still error
return 0;
}
root@Omkant:~/c# clang -std=c99 vararr.c -o vararr
vararr.c:8:11: error: variable-sized object may not be initialized
int Hello[a]={1,2,3,4,5,6};
^
1 error generated.
如果您删除静态并提供初始化,则会产生上述错误。
但如果你保持静态以及初始化,仍然会出错。
但如果你删除初始化并保留static,就会出现以下错误。
error: variable length array declaration not allowed at file scope
static int Hello[a];
^ ~
1 error generated.
因此,在文件范围内不允许可变长度数组声明,因此使其成为函数或任何函数内的块范围(但请记住使其成为函数范围必须删除初始化)
注意:由于它被标记为C,因此将a 和b 设置为const 对您没有帮助,但在C++ const 中可以正常工作。