我在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硬编码初始化,但此时不是结构中的结构。
有什么建议吗?
答案 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 }
}
}
};
似乎有效。请小心放置大括号,并尝试了解您输入的内容。这是如何阅读答案:
建议: