[英]An array of structures in C
For the life of me I can't figure out the proper syntax for creating an array of structures in C. I tried this: 对于我的生活,我无法弄清楚在C中创建结构数组的正确语法。我试过这个:
struct foo {
int x;
int y;
} foo[][] = {
{
{ 1, 2 },
{ 4, 5 },
{ -1, -1 }
},
{
{ 55, 44 }
{ 100, 200 },
}
};
So for example foo[1][0].x == 100, foo[0][1].y == 5, etc. But GCC spits out a lot of errors. 所以例如foo [1] [0] .x == 100,foo [0] [1] .y == 5等等。但是GCC吐出了很多错误。
If anyone could provide the proper syntax that'd be great. 如果有人能提供合适的语法,那将是伟大的。
EDIT: Okay, I tried this:
编辑:好的,我试过这个:
struct foo {
const char *x;
int y;
};
struct foo bar[2][] = {
{
{ "A", 1 },
{ "B", 2 },
{ NULL, -1 },
},
{
{ "AA", 11 },
{ "BB", 22 },
{ NULL, -1 },
},
{
{ "ZZ", 11 },
{ "YY", 22 },
{ NULL, -1 },
},
{
{ "XX", 11 },
{ "UU", 22 },
{ NULL, -1 },
},
};
But GCC gives me "elements of array bar have incomplete type" and "excess elements in array initializer". 但GCC给了我“数组条的元素有不完整的类型”和“数组初始化程序中的多余元素”。
This creates and initializes a two-dimensional array of structures, with each row containing three. 这将创建并初始化二维结构数组,每行包含三个。 Note that you haven't provided an initializer for the
array[1][2]
, which in this case means its contents is undefined. 请注意,您尚未为
array[1][2]
提供初始值设定项,在这种情况下,它的内容未定义。
struct foo {
const char *x;
int y;
};
int main()
{
struct foo array[][3] = {
{
{ "foo", 2 },
{ "bar", 5 },
{ "baz", -1 },
},
{
{ "moo", 44 },
{ "goo", 200 },
}
};
return 0;
}
EDIT: Made x pointer to const string. 编辑:指向const字符串的x指针。 Try to make your examples close to your real code.
尝试使您的示例接近您的真实代码。
I think the easiest approach would be to split up the struct and array declarations: 我认为最简单的方法是拆分结构和数组声明:
struct foo {
int x;
int y;
};
int main()
{
struct foo foo_inst = {1, 2};
struct foo foo_array[] = {
{5, 6},
{7, 11}
};
struct foo foo_matrix[][3] = {
{{5,6}, {7,11}},
{{1,2}, {3,4}, {5,6}}
};
return 0;
}
The problem is that nested array declarations in C (and C++) cannot have arbitrary length for any array except the outermost. 问题是C(和C ++)中的嵌套数组声明对于除最外层之外的任何数组都不能具有任意长度。 In other words, you can't say
int[][] arr
, and you must instead say int[][5] arr
. 换句话说,你不能说
int[][] arr
,你必须改为说int[][5] arr
。 Similarly, you can't say int[][6][] arr
or int [][][7] arr
, you would have to say int[][6][7] arr
. 同样,你不能说
int[][6][] arr
或int [][][7] arr
,你不得不说int[][6][7] arr
。
Your first problem is the declaration of the array. 你的第一个问题是数组的声明。 you can only leave the first square-bracket set empty.
你只能将第一个方括号设置为空。 the rest have to be explicitly declared.
其余的必须明确声明。
so instead of this: 所以不要这样:
struct foo bar[2][]
you should do this: 你应该做这个:
struct foo bar[][4]
This is really the first thing to sort out. 这是第一件要解决的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.