嵌套的struct变量初始化

时间:2009-11-19 08:47:42

标签: 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 ? */ };

4 个答案:

答案 0 :(得分:14)

将所有内容初始化为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) */

答案 1 :(得分:2)

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中就地初始化

答案 2 :(得分:1)

特别突出显示结构标签:

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

答案 3 :(得分:0)

以下内容也适用于GCC,C99。海湾合作委员会没有抱怨。我不确定这是否标准。

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