c - 此代码是否由 C 标准保证?

标签 c struct

我读过如果你像这样声明两个结构:

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 Nodestruct 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/

相关文章:

c - fgets如何在该程序中工作,如何与“流”概念联系在一起?

c - 有没有办法在 C 中增量处理格式说明符字符串?

swift - struct 中的 swift 类在分配期间是否通过副本传递?

c++ - 访问类中的结构成员

c - 如何在 makefile 中链接 C 库

c - 检查意外用户输入的方法

c++ - "lib"库前缀

c - typedef 一个结构到与该结构同名的点

c - malloc 一个结构指针数组,需要帮助

c# - 想知道一种在 C# 中使用 List<> 和结构来节省内存的方法