结构成员的内存布局 [英] struct members memory layout

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

问题描述

如果我有这样的结构:

struct S {
    ANY_TYPE a;
    ANY_TYPE b;
    ANY_TYPE c;
} s;

我可以安全地假定了以下假设永远是真正的所有平台上?

Can I safely assume that the following assumptions will always be true on all platforms?

((char *)&s.a) < ((char *)&s.c)
((char *)&s.a + sizeof(s.a) + sizeof(s.b)) <= ((char *)&s.c)

在C ++中吗?

推荐答案

是的,在C最少。编译器是免费的任何结构成员之后插入填充,但它绝不能重新排序的成员。

Yes, in C at least. The compiler is free to insert padding after any structure member but it must not reorder the members.

它还必须不是第一个成员之前插入填充。

It must also not insert padding before the first member.

从C99, 6.7.2.1

<强> 13 / 在一个结构物中,非位字段成员和在其中位场驻留有在其声明的顺序增加地址的单元。一个指向结构对象,合适的转换,指向其初始成员(如该成员是位字段,然后到单位所驻留),反之亦然。有可能是一个结构对象内无名填充,但不是在其开头。

13/ Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

15 / 有可能是未命名的填充在一个结构或联合的结束。

15/ There may be unnamed padding at the end of a structure or union.

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

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