How to initialize array structure elements in C

I have the following structure:

typedef struct { int someArray[3][2]; int someVar; } myStruct; 

If I create an array of this structure in my main (for example, the following), how would I initialize it?

 int main() { myStruct foo[5]; } 

I want to initialize the above structure array in the same way as initializing a regular array (see below):

 int main() { int someArray[5] = {1,4,0,8,2}; } 
+4
source share
3 answers

Work from the outside. You know that you have an array of 5 things to initialize:

 mystruct foo[5] = { X, X, X, X, X }; 

where X is the backup for mystruct type mystruct . So now we need to figure out what each X looks like. Each mystruct instance has two elements: somearray and somevar , so you know that your initializer for X will be structured as

 X = { Y, Z } 

Substituting back into the original ad, we get

 mystruct foo[5] = { { Y, Z }, { Y, Z }, { Y, Z }, { Y, Z }, { Y, Z } }; 

Now we need to find out what each Y looks like. Y corresponds to the initializer for the 3x2 array from int . Again, we can work from the outside. You have an initializer for a 3 element array:

 Y = { A, A, A } 

where each element of the array is a 2-element int array:

 A = { I, I } 

Returning to Y, we get

 Y = { { I, I }, { I, I }, { I, I } } 

Substituting this back into X, we get

 X = { { { I, I }, { I, I }, { I, I } }, Z } 

which now gives us

 mystruct foo[5] = { { { { I, I }, { I, I }, { I, I } }, Z }, { { { I, I }, { I, I }, { I, I } }, Z }, { { { I, I }, { I, I }, { I, I } }, Z }, { { { I, I }, { I, I }, { I, I } }, Z }, { { { I, I }, { I, I }, { I, I } }, Z } }; 

Since Z is a stand for an integer, we no longer need to split it. Just replace I and Z with real integer values ​​and you are done:

 mystruct foo[5] = { {{{101, 102}, {201, 202}, {301, 302}}, 41}, {{{111, 112}, {211, 212}, {311, 312}}, 42}, {{{121, 122}, {221, 222}, {321, 322}}, 43}, {{{131, 132}, {231, 232}, {331, 332}}, 44}, {{{141, 142}, {241, 242}, {341, 342}}, 45} }; 
+24
source

Wrap the initializer for each structural element of the array in a set of curly braces:

 myStruct foo[5] = { { { { 11, 12 }, { 13, 14 }, { 55, 56 }, }, 70 }, { { { 21, 22 }, { 23, 24 }, { 45, 66 }, }, 71 }, { { { 31, 32 }, { 33, 34 }, { 35, 76 }, }, 72 }, { { { 41, 42 }, { 43, 44 }, { 25, 86 }, }, 73 }, { { { 51, 52 }, { 53, 54 }, { 15, 96 }, }, 74 }, }; 
+3
source

Like:

 int main() { // someArr initialization | someVar initialization mystruct foo[5] = { { { {1, 2}, {1,2}, {1, 2} }, 1 }, // foo[0] initialization //... }; } 
0
source

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


All Articles