Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need more curly braces when initializing this structure?

Tags:

c

struct

At first I tried to initialize a structure like this:

struct {
    char age[2];        // Hold two 1-Byte ages
} studage[] = {
    {23, 56},
    {44, 26}
};

But that gives me a compiler warning about missing braces, so I used more braces as suggested by the compiler and ended up with this:

struct {
    char age[2];        // Hold two 1-Byte ages
} studage[] = {
    {{23, 56}},
    {{44, 26}}
};

No warning. Why do I need the extra braces?

like image 621
user3542317 Avatar asked Nov 04 '14 12:11

user3542317


1 Answers

You have an array of structs, the struct has one member which is an array.

struct {
    char age[2];        // Hold two 1-Byte ages
} studage[] = {
              ^ 
         This is for the studage array
    { { 23, 56}},
    ^ ^ 
    | this is for the age array
  this is for the anonymous struct

    {{44, 26}}
};

Perhaps it's easier to see if your struct had another member:

struct {
        int id;
        char age[2];
    } studage[] = {
        {1, {23, 56}},
         ^   ^    ^
         id  |    | 
           age[0] |
                 age[1]
     };
like image 181
nos Avatar answered Oct 10 '22 10:10

nos