gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:27:36 25 4
gpt4 key购买 nike

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

static char * name[] = {
[0x80000000] = "bar"
};

最佳答案

在C99中可以指定数组索引来赋值,例如:

static char * name[] = {
[3] = "bar"
};

等同于:

static char * name[] = { NULL, NULL, NULL, "bar"};

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

5.20 Designated Initializers:

In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C89 mode as well. This extension is not implemented in GNU C++. To specify an array index, write [index] = before the element value. For example,

 int a[6] = { [4] = 29, [2] = 15 };

is equivalent to

 int a[6] = { 0, 0, 15, 0, 29, 0 };

在 GNU 扩展中可以有一个更有趣的声明:

An alternative syntax for this which has been obsolete since GCC 2.5 but GCC still accepts is to write [index] before the element value, with no =.

To initialize a range of elements to the same value, write [first ... last] = value. For example,

 int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; 

注意:数组的长度是指定的最大值加一。

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

 int a[6] = { [1] = v1, v2, [4] = v4 };

相当于

 int a[6] = { 0, v1, v2, 0, v4, 0 };

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

 int whitespace[256]  = { [' '] = 1,  ['\t'] = 1, ['\h'] = 1,
['\f'] = 1, ['\n'] = 1, ['\r'] = 1
};

关于c - 奇怪的数组初始化表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18329206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com