sizeof(空结构)和sizeof(空数组结构)之间的区别?

Difference between sizeof(empty struct) and sizeof(struct with empty array)?

我有两个结构定义如下:

struct EmptyStruct{

};

struct StructEmptyArr{
    int arr[0];
};

int main(void){
    printf("sizeof(EmptyStruct) = %ld\n", sizeof(EmptyStruct));
    printf("sizeof(StructEmptyArr) = %ld\n", sizeof(StructEmptyArr));

    return 0;
}

在 Ubuntu 14.04、x64 上用 gcc (g++) 4.8.4 编译。

输出(对于 gcc 和 g++):

sizeof(EmptyStruct) = 1
sizeof(StructEmptyArr) = 0

我能理解为什么 sizeof(EmptyStruct) 等于 1 但不明白为什么 sizeof(StructEmptyArr) 等于 0。为什么两者有区别?

在 C 语言中,如果定义的结构没有任何命名成员,则程序的行为是未定义的。

C11-§6.7.2.1:

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.

GCC 允许空结构 an extension 并且其大小为 0.


对于 C++,the standard doesn't allow an object of size 0 因此 sizof(EmptyStruct) return 的值为 1。
标准 C++1 不支持零长度数组,但 supported as an extension by GNUsizeof 运算符将 return 0 如果应用。


1. § 8.5.1-脚注 107) C++ 没有零长度数组。

https://gcc.gnu.org/onlinedocs/gcc/Empty-Structures.html

G++ treats empty structures as if they had a single member of type char.

https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object.