所以我需要准备一个大型结构:
struct Config {
int a;
int b;
int c;
struct { int x; int y; } d[40];
};
我想这样填写:
Config config = {
.a = 3;
.b = 4;
.d[0] = {10, 12};
.d[1] = {14, 16};
};
在此之后,config.c
和config.d[2]
的值是否有未指定的值?还是零?
或者,我需要做:
Config config;
memset(&config, 0, sizeof(config));
config.a = 3;
config.b = 4;
config.d[0].x = 10;
config.d[0].y = 12;
...
最佳答案
它们被初始化为零。
来自 C99 标准,§6.7.8,第 19 项:
The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding anypreviously listed initializer for the same subobject; all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.
static
对象的初始化规则在前面的第 10 项中指定:
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;
- if it is a union, the first named member is initialized (recursively) according to these rules.
关于c - 当我们使用新的结构初始化格式时,未列出的成员是否有未指定的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706116/