C 嵌套结构变量初始化
如何在C中初始化这个嵌套结构C 嵌套结构变量初始化,c,struct,initialization,C,Struct,Initialization,如何在C中初始化这个嵌套结构 typedef struct _s0 { int size; double * elems; }StructInner ; typedef struct _s1 { StructInner a, b, c, d, e; long f; char[16] s; }StructOuter; StructOuter myvar = {/* what ? */ }; 似乎a和b不能在普通C中适当初始化,以将所有内容初始化为0(正确类型)
typedef struct _s0 {
int size;
double * elems;
}StructInner ;
typedef struct _s1 {
StructInner a, b, c, d, e;
long f;
char[16] s;
}StructOuter; StructOuter myvar = {/* what ? */ };
似乎a和b不能在普通C中适当初始化,以将所有内容初始化为0(正确类型) 将成员初始化为特定值的步骤
StructOuter myvar = {{0, NULL}, {0, NULL}, {0, NULL},
{0, NULL}, {0, NULL}, 42.0, "foo"};
/* that's {a, b, c, d, e, f, s} */
/* where each of a, b, c, d, e is {size, elems} */
编辑 如果您有C99编译器,还可以使用“指定的初始值设定项”,如中所示:
要特别突出显示结构标签,请执行以下操作:
StructInner a = {
.size: 1,
.elems: { 1.0, 2.0 }, /* optional comma */
};
StructOuter b = {
.a = a, /* struct labels start with a dot */
.b = a,
a, /* they are optional and you can mix-and-match */
a,
.e = { /* nested struct initialization */
.size: 1,
.elems: a.elems
},
.f = 1.0,
.s = "Hello", /* optional comma */
};
以下内容也适用于GCC、C99。GCC对此没有抱怨。我不确定这是否标准
double arr[] = { 1.0, 2.0 }; // should be static or global
StructOuter myvar =
{
.f = 42,
.s = "foo",
.a.size = 2,
.a.elems = &arr,
.b.size = 0, // you can explicitly show that it is zero
// missing members will actually be initialized to zero
};
应该是
chars[16]代码>,而不是char[16]s代码>在C++上有类似的帖子。为了澄清,<代码> Subutter MyVa= { 0 };将对所有内部结构执行相同的(0-初始化),因此我们不需要显式地将它们设置为{0,NULL}
,对吗?是的@domsson,{0}
初始值设定项将在需要时递归地对所有内容进行0-初始化。
StructOuter myvar = {.c = {1000, NULL}, .f = 42.0, .s = "foo"};
/* c, f, and s initialized to specific values */
/* a, b, d, and e will be initialized to 0 (of the right kind) */
StructInner a = {
.size: 1,
.elems: { 1.0, 2.0 }, /* optional comma */
};
StructOuter b = {
.a = a, /* struct labels start with a dot */
.b = a,
a, /* they are optional and you can mix-and-match */
a,
.e = { /* nested struct initialization */
.size: 1,
.elems: a.elems
},
.f = 1.0,
.s = "Hello", /* optional comma */
};
double arr[] = { 1.0, 2.0 }; // should be static or global
StructOuter myvar =
{
.f = 42,
.s = "foo",
.a.size = 2,
.a.elems = &arr,
.b.size = 0, // you can explicitly show that it is zero
// missing members will actually be initialized to zero
};