是C-结构与保证在内存相同的布局相同的成员类型? [英] Are C-structs with the same members types guaranteed to have the same layout in memory?
问题描述
从本质上讲,如果我有
typedef结构{
INT X;
诠释Ÿ;
} 一个;typedef结构{
INT H;
时int k;
} B:
和我有 A A
,请问C标准保证((B *)及一) - GT; k
相同唉
?
是C-结构与保证在内存相同的布局相同的成员类型?
块引用>几乎是肯定的。对我来说足够接近。
从n1516,第6.5.2.3条第6款:
...如果联合包含共享一个共同的初始序列...几种结构,如果联合对象当前包含这些结构中的一个,它被允许在任何地方,一个检查的任何它们的共同初始部分完成型工会的声明是可见的。两种结构共享的公共初始序列青霉>如果相应成员具有兼容的类型(并且,对于位字段,相同的宽度)为一个或多个初始成员的序列
块引用>这意味着,如果你有以下的code:
结构A {
INT X;
诠释Ÿ;
};结构B {
INT H;
时int k;
};工会{
结构一个一个;
结构B B;
} U;如果您分配给
u.a
,标准说,你可以从u.b
读出相应的值。它横跨合理性的界限表明结构A
和结构b
可以有不同的布局,考虑这一要求。这样的系统将在极端病态的。记住,标准还保证:
结构永远不会重陷presentations。
在一个结构中增加字段(
斧
总是前唉
)的地址。第一个字段的偏移始终为零。
然而,这是非常重要的<!/ H1>
您转述的问题,
做C标准保证
((B *)及一) - GT;·K
相同a.y
块引用>没有!而且它很明确地指出,他们是不一样的!
结构A {INT X; };
结构B {INT X; };
INT测试(int值)
{
结构一个一个;
a.x =价值;
返回((结构的b *)及一) - X的催化剂;
}这是一个别名冲突。
Essentially, if I have
typedef struct { int x; int y; } A; typedef struct { int h; int k; } B;
and I have
A a
, does the C standard guarantee that((B*)&a)->k
is the same asa.y
?解决方案Are C-structs with the same members types guaranteed to have the same layout in memory?
Almost yes. Close enough for me.
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;
If you assign to
u.a
, the standard says that you can read the corresponding values fromu.b
. It stretches the bounds of plausibility to suggest thatstruct a
andstruct 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.
Addresses of fields in a structure increase (
a.x
is always beforea.y
).The offset of the first field is always zero.
However, and this is important!
You rephrased the question,
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; }
This is an aliasing violation.
这篇关于是C-结构与保证在内存相同的布局相同的成员类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!