c - "Array index in initialiser exceeds array bounds"

标签 c gcc c99

我想利用 C99 指定的数组初始化程序来帮助使我的代码更加自记录,但我遇到了下面描述的问题。

假设我有一个枚举和一个将枚举映射到其他有用数据结构的数组,例如:

enum { STATE_IDLE = 0, STATE_WORKING, STATE_PANIC };
int32_t const g_stress_levels[3] = {
        [STATE_IDLE] = 10,
        [STATE_WORKING] = 40,
        [STATE_PANIC] = 90
};

使用 TDM-GCC-32 gcc 4.8.1 和 -std=c99 编译上述内容,不会出现任何警告。下面的代码片段不会,而是会引发错误“初始化程序中的数组索引超出数组边界”。

enum { STATE_IDLE = 0, STATE_WORKING, STATE_PANIC, TOTAL_STATES };
int32_t const g_stress_levels[TOTAL_STATES] = {
        [STATE_IDLE] = 10,
        [STATE_WORKING] = 40,
        [STATE_PANIC] = 90
};

The GCC docs状态“索引值必须是常量表达式,即使正在初始化的数组是自动的”。 然而,我一直认为 enum 是一个常量表达式,那么为什么会出现这种情况呢?

最佳答案

代码运行良好,符合预期*:

gsamaras@gsamaras-A15:~$ cat px.c
#include <stdint.h>

enum { STATE_IDLE = 0, STATE_WORKING, STATE_PANIC, TOTAL_STATES };
int32_t const g_stress_levels[TOTAL_STATES] = {
        [STATE_IDLE] = 10,
        [STATE_WORKING] = 40,
        [STATE_PANIC] = 90
};

int main(void) {
    return 0;
}
gsamaras@gsamaras-A15:~$ gcc -Wall -std=c99 -o px px.c
gsamaras@gsamaras-A15:~$ 

问题一定出在其他地方。您还现场查看here .

*<子> Can enum member be the size of an array in ANSI-C?

关于c - "Array index in initialiser exceeds array bounds",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099427/

相关文章:

c - LD:将共享库链接到静态库

转换可变位大小的有符号整数

c - C中的逻辑运算符和位分离计算(PIC编程)

c - 如何为在 Windows 上构建的 libxml2.dll 生成 list 文件?

c++ - argv[1] 仅包含 Visual C++ 2010 中第一个命令行参数的首字母

c - 在 C 中,仅在函数定义中而不是声明中添加 `const` 是否合法?

c - 在 C 中循环退出后使用 'for' 循环迭代器

c - c 中这个简单的 printf 输出背后的真正含义是什么?

android - 构建链接到其他非标准共享库的共享库

c - 没有完整路径的 gcc : error trying to exec 'cc1' : execvp: No such file or directory