结构硬编码初始化中的 C 结构

C struct within a struct hardcoded initialization

我在这里为 C99 做错了什么:

struct chess {
    struct coordinate {
        char piece;
        int alive;
    } pos[3];
}table[3] =
{
    {
      {'Q', (int)1},{'Q', (int)1},{'Q', (int)1},
      {'B', (int)1},{'B', (int)1},{'B', (int)1},
      {'K', (int)1},{'K', (int)1},{'K', (int)1},
    }
};

它给出错误:

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token

我希望能够访问数据,就像在一个结构中有一个结构:

table[row].pos[column].piece
table[row].pos[column].alive

我尝试了几个 combinations,并且 none 似乎适用于这种情况。我之前已经完成了以前的结构硬编码初始化,但这次不是结构中的结构。

有什么建议吗?

如上所述,尝试将 char 文字括在单引号中,并添加额外的大括号以使内部数组成为初始化列表。

struct chess
{
   struct coordinate
   {
       char piece;
       int alive;
   } pos[3];
}
table[3] =
{  // table of 3 struct chess instances...
   { // ... start of a struct chess with a single member of coordinate[3]...
      { // ... this is where the  coordinate[3] array starts... 
         // ... and those are the individual elements of the  coordinate[3] array
         {'Q', 1}, {'Q', 1}, {'Q', 1}
       }
    },
    {{{'B', 1}, {'B', 1}, {'B', 1}}},
    {{{'K', 1}, {'K', 1}, {'K', 1}}}
};
struct chess {
    struct coordinate {
        char piece;
        int alive;
    } pos[3];
} table[3] =
{
    {
        .pos = {{ .piece = 'Q', .alive = 1 },
                { .piece = 'Q', .alive = 1 },
                { .piece = 'Q', .alive = 1 }
               }
    },
    {
        .pos = {{ .piece = 'B', .alive = 1 },
                { .piece = 'B', .alive = 1 },
                { .piece = 'B', .alive = 1 }
               }
    },
    {
        .pos = {{ .piece = 'K', .alive = 1 },
                { .piece = 'K', .alive = 1 },
                { .piece = 'K', .alive = 1 }
               }
    }
};

这似乎有效。请注意您的牙套的放置,请尝试理解您输入的内容。这是阅读答案的方法:

  1. table[3] 是一个数组。所以初始化器以'{'开始,以'};'结束,每个元素由','分隔
  2. 这个数组的每个元素都是一个'struct chess'。所以每个子元素以'{'开始,以'}'结束
  3. 在每个 'struct chess' 中你有一个数组 'pos[3]'。于是再分子'{'和'}'
  4. 每个'pos'都是一个struct,所以有sub-sub-sub'{'和'}'
  5. 字段终于来了。 Use the C99 initializer list 让您的代码更简洁。 C中的双引号是char*,不是char。使用单引号

建议:

  • 尽量减少 "difficult-to-read" 代码量。它将为您服务
  • 我从不使用嵌套结构。需要时,将它们的代码分开并创建函数来初始化它们。
  • CPPReference有用
  • 为您的结构使用良好的变量名称和标识符。当我阅读'pos'时,我认为它是国际象棋上的一个位置((x,y)坐标与信息)。