Reputation: 313
I came across the following structure:
static struct {
unsigned char a[5];
} b[] = {
{1,1,1,1,1},
{2,2,2,2,2}
};
However, if it is being compiled I get the following warning "warning: missing braces around initializer [-Wmissing-braces]".
If I alter it like so:
static struct {
unsigned char a[5];
} b[] = {
{{1,1,1,1,1}},
{{2,2,2,2,2}}
};
Then the warning is gone. What is each curly brace standing for after "b[] = " ? The innermost curly braces are obviously? standing for the initialization of char a[5]. But what are the other braces standing for? Obviously? one of the other curly braces has to account for the structure array b[] but which one? And why is there, as it seems, a third curly brace neccessary and what is it standing for? This confuses me.
Upvotes: 1
Views: 119
Reputation: 108986
static struct {
unsigned char a[5];
} b[] = { // array b
{ // struct
{ // array a
1,1,1,1,1}},
{ // another struct
{2,2,2,2,2}}
};
Upvotes: 0
Reputation: 3774
{1,1,1,1,1}
- The five elements of an array.
{{1,1,1,1,1}}
- That's how you initialize a struct with a field which is an array of five int
s in this case.
{{{1,1,1,1,1}}, {{2,2,2,2,2}}}
- This is an array of two elements. Where each element is an instance of a struct as mentioned above.
Upvotes: 1
Reputation: 142005
int a[2] = { 1, 2 };
Ok. Now this:
int a[2][2] = { { 1, 2 } , { 3, 4 } };
Right? a[0][0] = 1
and a[0][1] = 2
and a[1][0] = 3
and a[1][1] = 4
. a[0]
is memcmp equal to (int[]){ 1, 2 }
and a[1]
is memcmp equal to (int[]){ 3, 4 }
.
Now this:
struct {
int a[2];
} b = { { 1, 2 } };
So the first {
}
stand for structure initialization and the inner stand for b.a
initialization. Now we make an array of structures:
struct b_s {
int a[2];
} b[] = {
{
{ 1, 2 },
},{
{ 3, 4, }
},
};
So the first braces stand for array b[]
initialization. The second one are for structure b[0]
to initialize. The third one are to initialize the b[0].a
array.
The b[0]
is memcmp equal to &(struct b_s){ {1, 2 } }
. The b[0].a
is memcmp equal to (int[2]){ 1, 2 }
. The b[0].a[0]
is equal to 1
.
Upvotes: 5
Reputation: 224546
Each brace corresponds to the start of a subobject (an object inside an aggregate object, such as an array or structure).
b[]
is an array, so the first brace introduces elements of the array.
Each b
is a structure, so the next brace introduces members of the structure.
The member a
inside b
is an array, so the next braces introduces elements of that array.
Upvotes: 1
Reputation: 27662
You have an array of structs containing arrays. Three pairs of braces.
Upvotes: 0