Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize members of an array of struct in C

Tags:

c

I have the following struct:

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

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

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

I want to initialize the above array of struct in a way similar to initilazing a normal array (see below):

int main() {
    int someArray[5] = {1,4,0,8,2};
}
like image 533
still.Learning Avatar asked Mar 12 '12 14:03

still.Learning


1 Answers

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

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

where X is a stand-in for initializers of type mystruct. So now we need to figure out what each X looks like. Each instance of mystruct has two elements, somearray and somevar, so you know your initializer for X will be structured like

X = { Y, Z }

Substituting back into the original declaration, we now get

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

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

Y = { A, A, A }

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

A = { I, I }

Subsituting back into Y, we get

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

Substituting that 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-in for an integer, we don't need to break it down any further. Just replace the Is and Zs with actual integer values, and you're 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}
                  };
like image 163
John Bode Avatar answered Sep 30 '22 07:09

John Bode