c++ - 零大小结构

标签 c++ c gcc

我注意到当使用 GCC 4.6 编译时,sizeof(Foo) 为 0,sizeof(Bar) 为 1。出于某种原因,将一个空数组添加到一个空结构中使其大小为0。我认为两个结构的大小必须相同。这是怎么回事?

struct Foo
{
    char x[];
};

struct Bar {};

最佳答案

C 标准不允许 struct 声明。 n1570中的6.7.2.1(8):

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 报告的值是没有意义的。

关于c++ - 零大小结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10971651/

相关文章:

c++ - 用于库编译的C/C++约定/工具链

c++ - 在对象的 d-tor 期间检测内存泄漏

c - 在 C 中使用 lockf 锁定文件不起作用

c - asm 中的不可能约束

c - mspgcc 中的意外结果

python - 使用 Cython 进行扩展,名称与源文件不同

c++ - 简单的 C 程序跟踪数组

c++ - 在带有 XCode 4.1 的 Mac OS X Lion 上找不到 OpenAL 的 AL/al.h

命令行参数可用于其他函数吗?

c++ - 避免被无符号整数除法签名