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

时间:2016-10-31 08:36:35

标签: c struct c99 hardcoded

我在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,似乎没有一个适用于这种情况。在此之前我已经完成了之前的struct硬编码初始化,但此时不是结构中的结构。

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

尝试将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}}}
};

答案 1 :(得分:4)

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. 分隔
  3. 这个数组的每个元素都是一个结构棋#'。所以每个子元素都以' {'并以'}'
  4. 结束
  5. 在每个结构国际象棋中你有一个数组' pos [3]'。所以另一个子' {'和'}'
  6. 每个' pos'是一个结构,所以有子子' {'和'}'
  7. 最后,字段在这里。 Use the C99 initializer list让您的代码更清晰。 C中的双引号是char *,而不是char。使用单引号
  8. 建议:

    • 尽量减少难以阅读的数量"码。它会为你服务
    • 我从不使用嵌套结构。在需要时,将它们的代码分开并创建将初始化它们的函数。
    • CPPReference很有用
    • 为结构使用好的变量名称和标识符。当我读到' pos'时,我认为它是国际象棋((x,y)坐标与信息的位置)。
相关问题