gpt4 book ai didi

c - C 中 struct 的指定初始值设定项和复合文字

转载 作者:太空狗 更新时间:2023-10-29 15:24:11 26 4
gpt4 key购买 nike

我有以下结构:

typedef struct my_struct {
int a;
int b;
int *c;
} my_struct;

是:

my_struct n = (my_struct) { .b = 3 };

相当于:

my_struct n = (my_struct) { .a = 0, .b = 3, .c = NULL };

关于:

my_struct n = (my_struct) { .b = 3, 0 };

最佳答案

它们应该像静态一样被初始化,我们可以在草案 C99 标准部分 6.7.8 Initialization paragraph 19 中找到这一点说(强调我的):

The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;132) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

如果后面的初始值设定项不是指示符,那么它将在该指示符之后的下一个字段中选取,这在 17 段中有介绍:

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.129) In contrast, a designation causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator.130)

根据 20 段,这递归地应用于子聚合:

If the aggregate or union contains elements or members that are aggregates or unions, these rules apply recursively to the subaggregates or contained unions

6.7.810 中可以找到初始化静态持续时间对象的规则:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules; [...]

关于c - C 中 struct 的指定初始值设定项和复合文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24936022/

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