2012-10-04 79 views
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]是結構的一個成員。那結構的大小怎麼沒有考慮呢?

+2

你期望'int a [0]'有多大? – glglgl

+0

只是一個瘋狂的猜測 - 一個[0]是零元素的數組,聲音邏輯大小爲零。 –

+0

int a [0]將零整數存儲在內存中。 – Nocturno

回答

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 } 

如果你沒有錢在您的銀行帳戶,你沒有錢在所有:)

0

一個array的零元素的大小爲0。您可以使用sizeof(a[0])進行檢查,所以不考慮結構的大小。

4

這實際上比較複雜,它可能看起來首先。

首先,成員int a[0]是標準C中的約束違規(「語法錯誤」)。您必須遇到由編譯器提供的擴展。大小爲零的

陣列常常通過預C99編譯器用於模擬的柔性陣列成員,具有語法int a[]無邊界作爲struct的最後一個成員的效果。

對於整個struct的大小,這樣一個數組本身不算數,但它可能施加對齊約束。特別是,它可能會添加填充到結構的其他部分的末尾。如果你會做同樣的測試

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

(與[0],如果你的編譯器需要它),你最有可能看到的大小爲48它,因爲這些都是double平時對齊要求。