嵌套的struct变量初始化

如何在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 ? */ }; 

将所有内容初始化为0(正确类型)

 StructOuter myvar = {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编译器,您还可以使用“指定的初始值设定项”,如下所示:

 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) */ 
 double a[] = { 1.0, 2.0 }; double b[] = { 1.0, 2.0, 3.0 }; StructOuter myvar = { { 2, a }, { 3, b }, { 2, a }, { 3, b }, { 2, a }, 1, "a" }; 

似乎a和b不能在普通C中就地初始化

要突出显示结构标签:

 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 */ };