2012-06-10 74 views
12

我注意到,當使用GCC 4.6 sizeof(Foo)編譯爲0且sizeof(Bar)是1由於某種原因,將一個空數組到一個空的結構作出了大小爲0我認爲兩個結構的大小必須是相同的。這裏發生了什麼?零尺寸結構

struct Foo 
{ 
    char x[]; 
}; 

struct Bar {}; 
+1

奇怪的是,'sizeof'永遠不會_0 _.. –

+0

@ K-ballo:對於像'char x []'這樣的靈活數組,sizeof爲0. – Tudor

+0

@Tudor:靈活的數組,是一個編譯器擴展嗎? –

回答

16

C標準允許struct聲明。 6.7.2.1(8)在n1570:

If the struct-declaration-list does not contain any named members, either directly or via an anonymous structure or anonymous union, the behavior is undefined.

並且以相同的節段18:

As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

(重點煤礦)

彈性陣列成員不是在C++中允許的,所以代碼也是無效的C++。

由於它不是有效的代碼,因此sizeof報告的這些值是沒有意義的。

1

即使對於空的類,sizeof運算符也不會產生0。

,你可以看到here on msdn

而且在MSDN中指出:

sizeof操作符不能與下列操作數使用:

  • 功能。 (但是,sizeof可以應用於指向函數的指針。)
  • 位域。
  • 未定義的類。
  • 類型void。
  • 動態分配的數組。
  • 外部陣列。
  • 不完整的類型。
  • 不完整類型的括號名稱。
1

C和C++不允許零大小的對象。

gcc確實支持他們作爲擴展。如果你用適當的選項編譯,比如

gcc -std=c99 -pedantic -Wall -Wextra 

gcc至少會提醒你關於它們; g ++有類似的選項。