零大小结构 [英] Zero size struct

查看:164
本文介绍了零大小结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当使用GCC 4.6编译的sizeof(富) 0和的sizeof(酒吧) 1 。出于某种原因,添加一个空数组到一个空的结构做了它的大小为0我想,这两种结构的尺寸必须是相同的。这到底是怎么回事呢?

 结构美孚
{
    焦X [];
};结构酒吧{};


解决方案

无论是结构声明是由C标准允许的。 6.7.2.1(8)n1570:


  

如果在结构声明列表中不包含任何名称的成员,直接或通过匿名结构或匿名联合的行为是理解过程网络定义。


而在同一节第18段:


  

作为一个特殊的情况下,结构的与多个命名成员的最后一个元素可能有一个不完整的数组类型;这就是所谓的灵活的数组成员。在大多数情况下,灵活的阵列成员被忽略。具体地,结构的尺寸是因为如果灵活的阵列成员,不​​同的是它可以具有更拖尾填充比遗漏将意味着被删去。


(重点煤矿)

灵活的阵列成员不是在C ++中允许的,所以code是无效的C ++两种。

由于它是不是有效的code,由的sizeof 这些报告的值都是没有意义的。

I noticed that when compiled with GCC 4.6 sizeof(Foo) is 0 and sizeof(Bar) is 1. For some reason adding an empty array into an empty structure made its size 0. I thought that the sizes of both structures must be the same. What is going on here?

struct Foo
{
    char x[];
};

struct Bar {};

解决方案

Neither struct declaration is allowed by the C standard. 6.7.2.1 (8) in n1570:

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.

And paragraph 18 in the same section:

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.

(emphasis mine)

Flexible array members are not allowed in C++, so the code is not valid C++ either.

As it is not valid code, the values reported by sizeof for these are meaningless.

这篇关于零大小结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆