【问题标题】:Nested struct variable initialization嵌套结构变量初始化
【发布时间】:2009-11-19 08:47:42
【问题描述】:

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

【问题讨论】:

  • 应该是char s[16];,而不是char[16] s;
  • 在 SO for C++ 上有类似的帖子 here

标签: c struct initialization


【解决方案1】:

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

【讨论】:

  • 澄清一下,StructOuter myvar = { 0 }; 将对所有内部结构执行相同的操作(0 初始化),因此我们不需要将它们显式设置为 {0, NULL},对吧?
  • 是的@domsson,{ 0 } 初始化程序将在需要时递归地初始化所有内容。
【解决方案2】:

特别要突出显示结构标签:

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

    【讨论】:

      【解决方案4】:

      以下也适用于 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
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多