当我遇到问题时,我正在编写一个迷你GTK + 2.0游戏。当我这样写:
const unsigned LABEL_NUMBER = 4;
const char *LABEL_TEXT[4] = {
"Five or More",
"By ... "
"& ...",
"April 2016",
"~~ Thanks for playing ~~"
};
没有问题。但是当我写这篇文章时:
const unsigned LABEL_NUMBER = 4;
const char *LABEL_TEXT[LABEL_NUMBER] = {
"Five or More",
"By ... "
"& ...",
"April 2016",
"~~ Thanks for playing ~~"
};
gcc答案:
source/gui.c: In function ‘create_about_window’:
source/gui.c:202:4: error: variable-sized object may not be initialized
const char *LABEL_TEXT[LABEL_NUMBER] = {
^
source/gui.c:203:34: error: excess elements in array initializer [-Werror]
"Five or More",
^
source/gui.c:203:34: note: (near initialization for ‘LABEL_TEXT’)
source/gui.c:204:34: error: excess elements in array initializer [-Werror]
"By ... & ..."
^
source/gui.c:204:34: note: (near initialization for ‘LABEL_TEXT’)
source/gui.c:206:34: error: excess elements in array initializer [-Werror]
"April 2016",
^
source/gui.c:206:34: note: (near initialization for ‘LABEL_TEXT’)
source/gui.c:207:34: error: excess elements in array initializer [-Werror]
"~~ Thanks for playing ~~"
^
source/gui.c:207:34: note: (near initialization for ‘LABEL_TEXT’)
所以我只是想知道为什么gcc在使用常量无符号整数来设置数组大小时会显示这些错误?
答案 0 :(得分:1)
使用初始化程序无法初始化可变长度数组。
C11 - §6.7.9/ 3:
要初始化的实体的类型应为未知大小的数组或不是可变长度数组类型的完整对象类型。
答案 1 :(得分:0)
您可以将LABEL_NUMBER定义为宏:
#define LABEL_NUMBER 4
那样LABEL_NUMBER
const char *LABEL_TEXT[LABEL_NUMBER]
将在预处理阶段由定义的宏值替换 将产生:
const char *LABEL_TEXT[4]
编译器要编译。