簡體   English   中英

C中文件范圍內可變修改的數組

[英]variably modified array at file scope in 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

這樣預處理器將用6替換a ,使其有效聲明。

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 <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標記的,因此將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

是的,這很煩人:

const int len = 10;

int stuff[len];

給出錯誤。 我試圖避免使用 #define x,因為 const int 是一種更好的聲明常量的方式,但是在這些情況下,const int 不是真正的常量,即使編譯器很清楚它是。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM