C中文件范围的可变修改数组

我有一些像这样的代码:

static int a = 6; static int b = 3; static int Hello[a][b] = { { 1,2,3}, { 1,2,3}, { 1,2,3}, { 1,2,3}, { 1,2,3}, { 1,2,3} }; 

但是当我编译它时,它说错误:

在文件范围内可变地修改了“Hello”

怎么会发生这种情况? 我该怎么办呢?

您不能将静态数组作为变量给出

这就是为什么常量应该是#define d:

 #define a 6 

这样预处理器将替换a 6 ,使其成为有效声明。

variable modified array at file scope is not possible简单的答案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  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因此将ab作为const将无法帮助您,但在C++ const将正常工作。

使用CLANG / LLVM时,以下工作原理:

 static const int a = 6; static const int b = 3; static int Hello[a][b] = { { 1,2,3}, { 1,2,3}, { 1,2,3}, { 1,2,3}, { 1,2,3}, { 1,2,3} }; 

(要在生成的程序集中查看它,需要使用Hello,因此不会对其进行优化)

但是,如果选择了C99模式(-std = c99),这将产生错误,如果选择了-pedantic,它将仅生成警告(Wgnu-folding-constant)。

GCC似乎不允许这样(const被解释为只读)

请参阅此主题中的说明:

“初始化器元素不是常量”错误在Linux GCC中没有任何理由,编译C