2014-11-04 94 views
5

起初,我試圖初始化像這樣的結構:爲什麼初始化這個結構時需要更多花括號?

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

但是,這給了我一個編譯器警告失蹤牙套,所以我用多個支架由編譯器的建議,並結束了與此:

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

沒有警告。爲什麼我需要額外的大括號?

+5

是不是外一個用於結構和內部一個char數組裏面呢? – Wookie88 2014-11-04 12:59:20

+0

這是一個警告,而不是一個錯誤。編譯器不會「要求」任何東西。 – 2014-11-04 12:59:25

+2

[雙捲曲花括號初始化C結構的意義是什麼?](http://stackoverflow.com/questions/6251160/what-is-the-meaning-of-double-curly-braces-initializing- ac-struct)? – nicael 2014-11-04 13:02:12

回答

10

你有一個結構數組,結構有一個成員是一個數組。

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}} 
}; 

也許是更容易地看到,如果你的結構有另一名成員:

struct { 
     int id; 
     char age[2]; 
    } studage[] = { 
     {1, {23, 56}}, 
     ^^^
     id | | 
      age[0] | 
       age[1] 
    };