1
      1 #include <stdio.h>
      2 
      3 
      4 struct test {
      5     char c;
      6     int i;
      7     double d;
      8     void *p;
      9     int a[0];
     10 };  
     11     
     12 int main (void) {
     13     struct test t;
     14     printf("size of struct is: %d\n", sizeof(t));
     15     return 0;
     16 }

出力:

size of struct is: 20

なぜint a[0]考慮されないのですか?

私は試した:

  1 #include <stdio.h>
  2 
  3 
  4 struct test {
  5     int a[0];
  6 };  
  7     
  8 int main (void) {
  9     struct test t;
 10     printf("size of struct is: %d\n", sizeof(t));
 11     return 0;
 12 }

そして出力:

size of struct is: 0

a[0]構造体のメンバーです。では、なぜ構造の大きさに考慮されていないのでしょうか。

4

3 に答える 3

4

これは実際には、そもそも見た目よりも複雑です。

まず、メンバーint a[0]は標準Cの制約違反(「構文エラー」)です。コンパイラーによって提供される拡張機能に遭遇する必要があります。

サイズがゼロの配列は、C99より前のコンパイラで、柔軟な配列メンバーの効果をエミュレートするためによく使用されていました。柔軟な配列メンバーint a[]は、の最後のメンバーとして境界のない構文を持っていますstruct

全体のサイズについては、structそのような配列はそれ自体ではカウントされませんが、配置の制約が課せられる可能性があります。特に、構造の他の部分の終わりにパディングを追加する場合があります。同じテストを行う場合

struct toto {
   char name[3];
   double a[];
};

(コンパイラがそれを必要とする場合)、これらは通常のアライメント要件であるため、[0]おそらくそのサイズ4またはサイズが表示されます。8double

于 2012-10-04T07:40:38.263 に答える
1

これを試してください:

 1 #include <stdio.h>
  2 
  3 
  4 struct test {
  5     int a[0];
  6 };  
  7     
  8 int main (void) {
  9     struct test t;
 10     printf("size of struct is: %d\n", sizeof(t)==sizeof(t.a));
 11     return 0;
 12 }

銀行口座にお金がない場合は、まったくお金がありません:)

于 2012-10-04T06:53:41.157 に答える
0

array要素がゼロの a のサイズは で0確認できるsizeof(a[0])ので、構造体のサイズには考慮されません。

于 2012-10-04T07:02:03.150 に答える