是否保证具有相同成员类型的 C 结构在内存中具有相同的布局? [英] Are C-structs with the same members types guaranteed to have the same layout in memory?
问题描述
基本上,如果我有
typedef struct {
int x;
int y;
} A;
typedef struct {
int h;
int k;
} B;
而且我有 A a
,C 标准是否保证 ((B*)&a)->k
与 ay 相同
?
and I have A a
, does the C standard guarantee that ((B*)&a)->k
is the same as a.y
?
推荐答案
是否保证具有相同成员类型的 C 结构在内存中具有相同的布局?
Are C-structs with the same members types guaranteed to have the same layout in memory?
几乎是的.对我来说足够接近了.
Almost yes. Close enough for me.
来自 n1516,第 6.5.2.3 节,第 6 段:
From n1516, Section 6.5.2.3, paragraph 6:
... 如果联合包含多个共享公共初始序列的结构...,并且联合对象当前包含这些结构之一,则允许检查其中任何一个的公共初始部分联合的完成类型的声明是可见的.如果对应的成员对于一个或多个初始成员的序列具有兼容的类型(并且对于位域,具有相同的宽度),则两个结构共享一个公共初始序列.
... if a union contains several structures that share a common initial sequence ..., and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.
这意味着如果您有以下代码:
This means that if you have the following code:
struct a {
int x;
int y;
};
struct b {
int h;
int k;
};
union {
struct a a;
struct b b;
} u;
如果你赋值给u.a
,标准说你可以从u.b
中读取相应的值.它扩展了合理性的界限,建议 struct a
和 struct b
可以有不同的布局,给定这个要求.这样的系统在极端情况下是病态的.
If you assign to u.a
, the standard says that you can read the corresponding values from u.b
. It stretches the bounds of plausibility to suggest that struct a
and struct b
can have different layout, given this requirement. Such a system would be pathological in the extreme.
请记住,该标准还保证:
Remember that the standard also guarantees that:
结构绝不是陷阱表示.
Structures are never trap representations.
结构中字段的地址增加(a.x
总是在 a.y
之前).
Addresses of fields in a structure increase (a.x
is always before a.y
).
第一个字段的偏移量始终为零.
The offset of the first field is always zero.
你改写了这个问题,
C 标准是否保证 ((B*)&a)->k
与 a.y 相同?
does the C standard guarantee that
((B*)&a)->k
is the same as a.y?
不!它非常明确地指出它们不一样!
No! And it very explicitly states that they are not the same!
struct a { int x; };
struct b { int x; };
int test(int value)
{
struct a a;
a.x = value;
return ((struct b *) &a)->x;
}
这是别名违规.
这篇关于是否保证具有相同成员类型的 C 结构在内存中具有相同的布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!