我有两个结构体定义如下:
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)
返回值 1。
标准 C++¹ 不支持长度为零的数组,但 supported as an extension by GNU如果应用 sizeof
运算符将返回 0
。
1. § 8.5.1-footnote 107) C++ 没有零长度数组。
关于c++ - sizeof(空结构)和 sizeof(带有空数组的结构)之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45194751/