c++ - sizeof(空结构)和 sizeof(带有空数组的结构)之间的区别?

标签 c++ c struct sizeof

我有两个结构体定义如下:

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/

相关文章:

C++ Bitset 数组,访问值

c++ - 如何在 C++ 中使友元类的友元函数直接访问其私有(private)成员

c - 有没有一种简单的方法来清除 C 中的管道

C 数组结构声明

c++ - 递归 C++ 阶乘为多个条目提供负值

c++ - C++03 中的右值

c - 一些链表C宏的问题

c - SHA256 有 table cli 和 openssl 库

c - 二叉搜索树查找输出

arrays - 为什么这个具有可选值的结构不返回任何内容?