Array of Structures in C

In life, I cannot understand the correct syntax for creating an array of structures in C. I have tried this:

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 mistakes.

If someone can provide the correct syntax, that will be great.

EDIT: Ok, 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 “the elements of the bar array are of an incomplete type” and “the extra elements in the array initializer”.

+4
source share
3 answers

This creates and initializes a two-dimensional array of structures, with each row containing three. Note that you did not specify an initializer for array[1][2] , which in this case means that its contents are undefined.

 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: pointer x for the string const. Try to make your examples close to your real code.

+7
source

I think the simplest approach would be to separate the declarations of the structure and the array:

 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 declarations of nested arrays in C (and C ++) cannot have arbitrary lengths for any array except the outermost one. In other words, you cannot say int[][] arr , and instead you should say int[][5] arr . Similarly, you cannot say int[][6][] arr or int [][][7] arr , you must say int[][6][7] arr .

+2
source

Your first problem is declaring an array. you can leave an empty square square. the rest must be explicitly declared.

so instead:

 struct foo bar[2][] 

you should do this:

 struct foo bar[][4] 

This is really the first thing to figure out.

0
source

Source: https://habr.com/ru/post/1308071/


All Articles