我读过如果你像这样声明两个结构:
struct Node {
int a, b, c;
};
struct DerivedNode {
struct Node base;
int d, e, f;
};
然后你可以像这样使用指向它们的指针:
struct DerivedNode myDerivedNode;
struct Node *regularNode = (struct Node *) &myDerivedNode;
regularNode->a = 3;
换句话说,a, b, c
的地址偏移量在 struct Node
和 struct DerivedNode
中是相同的。因此,您可以从中获得一种多态性,您可以在其中强行传递 (struct Node *)
-cast DerivedNode 指针,无论通常采用 Node 指针的地方。
我的问题是这种行为是否得到保证。我知道有一些奇怪的内存对齐问题,编译器有时会重新排序字段以实现更好的内存打包。 base
字段是否会位于 struct DerivedNode
开头以外的任何位置?
最佳答案
这保证按标准工作。结构中的成员按您指定的顺序排列,第一个成员始终出现在偏移量 0 处。
ANSI C 标准的相关摘录:
A structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence.
这说明成员是按顺序排列的。
There may be unnamed padding within a structure object, but not at its beginning.
这意味着第一个成员被放置在偏移量 0 处。
注意:标准摘录自 ISO/IEC 9899:TC3 2007 年 9 月草案第 6.7.2.1 节。
关于c - 此代码是否由 C 标准保证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7725431/