【问题标题】:Why do I need more curly braces when initializing this structure?为什么初始化这个结构时需要更多的花括号?
【发布时间】:2014-11-04 12:56:31
【问题描述】:

一开始我尝试初始化一个这样的结构:

struct {
    char age[2];        // Hold two 1-Byte ages
} studage[] = {
    {23, 56},
    {44, 26}
};

但这给了我一个关于缺少大括号的编译器警告,所以我按照编译器的建议使用了更多的大括号,结果如下:

struct {
    char age[2];        // Hold two 1-Byte ages
} studage[] = {
    {{23, 56}},
    {{44, 26}}
};

没有警告。为什么我需要额外的大括号?

【问题讨论】:

  • 外面的不是结构体,里面的不是char数组吗?
  • 这是一个警告,而不是错误。编译器没有“要求”任何东西。
  • 目前不相关,并且可能仅当您正在处理旧事物的时代时,但在 C 中,char 可能是 signedunsigned,具体取决于您的平台。使用unsigned char 更安全(除非您正在处理根据某些物理模型可能具有负年龄的负能量反粒子。)
  • §6.7.9/30 说“请注意,初始化的完全括号和最小括号形式通常不太可能引起混淆。”

标签: c struct


【解决方案1】:

你有一个结构数组,这个结构有一个成员是一个数组。

struct {
    char age[2];        // Hold two 1-Byte ages
} studage[] = {
              ^ 
         This is for the studage array
    { { 23, 56}},
    ^ ^ 
    | this is for the age array
  this is for the anonymous struct

    {{44, 26}}
};

也许更容易查看您的结构是否有其他成员:

struct {
        int id;
        char age[2];
    } studage[] = {
        {1, {23, 56}},
         ^   ^    ^
         id  |    | 
           age[0] |
                 age[1]
     };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 2021-07-14
    • 2020-10-20
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多