关于 C struct packing 有什么保证吗?

Are there any guarantees about C struct packing?

在 C 中是否有任何关于结构打包的保证?

举个例子,假设sizeof(double) == 8,是否保证sizeof(struct { double x, y; }) == 16

我知道这个问题背后的意图与严格的别名规则冲突,因此假设禁用了严格的别名,例如对于 -fno-strict-aliasing.

的 gcc

为了避免任何进一步的推测:目的是了解结构与其明确打包的对应结构的兼容性。请注意,即使在以下情况下,别名也是相关的:具有相同成员类型的 C 结构是否保证在内存中具有相同的布局? 。不用担心我想要访问单个字节。

C 标准关于结构打包的唯一说明是 struct 的开头不能存在填充。它不保证字段之间或末尾的填充。

C standard 的第 6.7.2.1 节说明了以下关于结构的内容:

15 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.

...

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

也就是说,大多数实现往往与结构的打包方式相当一致。大小为 n 字节的非结构变量(或此类变量的数组)将倾向于从 n 字节边界开始。结构中的结构将倾向于根据其子字段的对齐方式进行对齐。

The Lost Art of C Structure Packing 对此进行了更详细的介绍。