gpt4 book ai didi

c++ - 零大小结构

转载 作者:IT老高 更新时间:2023-10-28 23:14:47 25 4
gpt4 key购买 nike

我注意到当使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com