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

30 c arrays static

我有一些像这样的代码:

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}
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

zch*_*zch 46

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

这就是为什么常数应该是#defined:

#define a 6
Run Code Online (Sandbox Code Playgroud)

这样预处理器将替换a6,使其成为有效声明.

  • 宏的替代方法是使用匿名枚举,它们是真正的整数常量 `enum { a = 6, b = 3, };` (7认同)
  • 不,这仍然是一个变量。使用“#define”。在 C++ 中,有 `const` 可以让 `const int a = 6;` 工作,但在 C 中即使是 `const` 也是不够的。 (3认同)

Omk*_*ant 9

简单回答variable modified array at file scope is not possible.

详细:

使编译时间integral constant expression,因为必须在编译时指定数组长度.

像这样 :

#define a 6
#define b 3
Run Code Online (Sandbox Code Playgroud)

或者,遵循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.
}
Run Code Online (Sandbox Code Playgroud)

现在使用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. 
Run Code Online (Sandbox Code Playgroud)

如果删除静态并提供初始化,则会产生上述错误.

但是如果你保持静态和初始化,那么仍然会出错.

但如果你删除初始化并保持static以下错误将来.

error: variable length array declaration not allowed at file scope
static int Hello[a];
           ^     ~
1 error generated.
Run Code Online (Sandbox Code Playgroud)

因此,在文件范围内不允许使用可变长度数组声明,因此在任何函数内部使其成为函数或块作用域(但请记住使其功能范围必须删除初始化)

注:由于它C贴上标签,以制作a,并bconst不会帮助你,但在C++ const将正常工作.

  • C99 也不支持文件范围内的 VLA。它必须在函数范围内或更小。他“可以”在文件范围内使用 **const** 索引声明,包括“static const int a = 10;”。 (3认同)