奇怪的数组初始化表达式?

ted*_*ted 20 c arrays compiler-construction gcc

以下代码是什么意思?代码来自GCC的回归测试套件.

static char * name[] = {
   [0x80000000]  = "bar"
};
Run Code Online (Sandbox Code Playgroud)

Gri*_*han 25

在C99中,您可以将数组索引指定为指定的值,例如:

static char * name[] = {
   [3]  = "bar"  
};
Run Code Online (Sandbox Code Playgroud)

与:

static char * name[] = { NULL, NULL, NULL, "bar"};
Run Code Online (Sandbox Code Playgroud)

数组的大小是四.检查在ideaone上工作的示例代码.在您的代码数组中,大小是0x80000001(十六进制数).
注意:初始化的未初始化元素0.

5.20指定的初始化器:

在ISO C99中,您可以按任何顺序给出元素,指定它们适用的数组索引或结构字段名称,GNU C也允许它作为C89模式的扩展.此扩展未在GNU C++中实现.要指定数组索引,请[index] =在元素值之前写入.例如,

 int a[6] = { [4] = 29, [2] = 15 };
Run Code Online (Sandbox Code Playgroud)

相当于

 int a[6] = { 0, 0, 15, 0, 29, 0 };
Run Code Online (Sandbox Code Playgroud)

在GNU扩展中可能还有一个有趣的声明:

自GCC 2.5以来已经过时但GCC仍然接受的另一种语法是[index]在元素值之前写入,没有=.

要将一系列元素初始化为相同的值,请写入[first ... last] = value.例如,

 int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; 
Run Code Online (Sandbox Code Playgroud)

注意:数组的长度是指定的最高值加1.

另外,我们可以将这种命名元素技术与连续元素的普通C初始化相结合.每个没有指示符的初始化元素都适用于数组或结构的下一个连续元素.例如:

 int a[6] = { [1] = v1, v2, [4] = v4 };
Run Code Online (Sandbox Code Playgroud)

相当于

 int a[6] = { 0, v1, v2, 0, v4, 0 };
Run Code Online (Sandbox Code Playgroud)

当索引是字符或属于枚举类型时,标记数组初始值设定项的元素特别有用.例如:

 int whitespace[256]  = { [' '] = 1,  ['\t'] = 1, ['\h'] = 1,
                          ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 
                        };
Run Code Online (Sandbox Code Playgroud)


Yu *_*Hao 8

它被称为指定的初始化程序,它是在C99中引入的,gcc也支持GNU89作为扩展,详见此处.

 int a[6] = { [4] = 29, [2] = 15 };
Run Code Online (Sandbox Code Playgroud)

相当于

 int a[6] = { 0, 0, 15, 0, 29, 0 };
Run Code Online (Sandbox Code Playgroud)


lus*_*oog 5

它是C99 指定的初始化程序.括号中的值指定接收值的索引.