簡體   English   中英

初始化元素在Clang / GCC中不是恆定的

[英]Initializer element is not constant in Clang/GCC

我最近一直在制作Roguelike,並且使用以下特定代碼遇到編譯錯誤:

typedef const char* string;

typedef struct {
string name;
string desc;
int dice;
int sides;
} weapon;

typedef struct {
string name;
string desc;
int dice;
int sides;
} armor;

typedef struct {
string name;
char icon;
int x;
int y;
weapon wep;
armor arm;
int hp;
int maxhp;
} creature;

這在頭文件中。

另一個文件定義了外部變量:

extern creature monsters[MAX_MONSTERS];
extern creature level_cre[MAX_LEVELCRE];
extern weapon weapons[MAX_WEAPONS];
extern armor armors[MAX_ARMORS];

在定義武器和裝甲陣列的文件中:

weapon weapons[MAX_WEAPONS] = {
    {"Sword", "A steel sword", 1, 6},
};

armor armors[MAX_ARMORS] = {
    {"Leather", "Leather armor", 1, 10},
};

還有給我一個錯誤的部分:

creature monsters[MAX_MONSTERS] = {
    {"Skeleton", 's', 0, 0, weapons[0], armors[0], 100, 100},
    {"Orc", 'o', 0, 0, weapons[0], armors[0], 100, 100},
};

運行此命令會給我標題帶來錯誤,在進行了一些研究后,似乎是由於未正確定義常量而引起的。 我在這里完全不知所措。 任何幫助,將不勝感激。 :)

ISO / IEC 9899:201x初始化 ,§4:

具有靜態或線程存儲持續時間的對象的初始化程序中的所有表達式應為常量表達式或字符串文字。

ISO / IEC 9899:201x常數表達式 ,§7:

初始化程序中的常量表達式允許更大的自由度。 該常數表達式應為以下值之一或計算為以下值之一:
—算術常數表達式,
—空指針常量,
—地址常量,或
—完整對象類型的地址常量,加上或減去整數常量表達式。

weapons[0]armors[0]都不是以上內容。 但是正如奧拉夫建議的那樣,您可以更改為

weapon *wep;
armor *arm;
…
    {"Skeleton", 's', 0, 0, &weapons[0], &armors[0], 100, 100},
    {"Orc",      'o', 0, 0, &weapons[0], &armors[0], 100, 100},

- &weapons[0]&armors[0]是地址常量,因此可在初始化程序中使用。

暫無
暫無

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

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