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};
}
Work from the outside in. You know you have an array of 5 things to initialize:
where
Xis a stand-in for initializers of typemystruct. So now we need to figure out what eachXlooks like. Each instance ofmystructhas two elements,somearrayandsomevar, so you know your initializer forXwill be structured likeSubstituting back into the original declaration, we now get
Now we need to figure out what each Y looks like. Y corresponds to an initializer for a 3×2 array of
int. Again, we can work from the outside in. You have an initializer for a 3-element array:where each array element is a 2-element array of
int:Subsituting back into Y, we get
Substituting that back into X, we get
which now gives us
Since
Zis a stand-in for an integer, we don’t need to break it down any further. Just replace theIs andZs with actual integer values, and you’re done: