c - C union 中的变量对齐方式在所有系统上都相同吗?

标签 c memory struct unions

考虑以下 union :

typedef union {
    struct { // Anonymous struct
        int red;
        int green;
        int blue;
    };
    int colorChannels[3];
} Color;

不管这段代码在哪个系统上编译或执行,匿名结构中的字段是否总是与 colorChannels 中的索引对齐?

也就是说,规范是否要求myColor.colorChannels[0]的内存地址与myColor.red的地址相同?

另外,如果将代码编译为 C++ 而不是 C,答案会有所不同吗?

请注意,我询问的是 union 中的每个元素都具有相同类型/大小的特定情况(即在这种情况下为 int)

最佳答案

Regardless of the system this code is compiled or executed on, will the fields in the anonymous struct always line up with the indexes in colorChannels?

不一定。该实现可以在 struct 的各个变量之间添加字节“填充”。 “填充”只是以实现定义的方式插入到 struct 的变量之间或末尾的内存定义中的额外内存字节。如果发生这种情况,那么您的整数数组将不会与 struct 的内存布局对齐(除非填充仅位于 struct 的末尾)。内存中 struct 中变量的顺序在不同的实现中应该是一致的(在那个变量 a 后面是 b 后面是 c 在内存中),但是,同样,之间的字节填充仍然可以存在(例如,a 后跟 b 在内存中但有填充在 ab 之间,这样它们在内存中就不会彼此紧接)。

对于像 gcc 这样的一些编译器,there are ways to modify how it handles padding .这可以帮助保证 struct 与您的整数数组在内存中对齐,但这可能会导致下游的其他内存问题。

In other words, does the specification require the memory address of myColor.colorChannels[0] to be the same as the address of myColor.red?

如果 structredgreenblue 之间没有填充,则索引colorChannels 将与内存中的每个变量匹配。

关于c - C union 中的变量对齐方式在所有系统上都相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48938642/

相关文章:

c - 访问函数中的结构元素

java - 再次调用函数比将其分配给变量更好

c - 结构体元素的初始化

c - 在 C 中将双指针作为参数传递

c - 无法从用户空间读取 iio 文件

编译器不给出错误 undefined reference 的行号

javascript - 为什么 node.js 进程占用的内存比分配的多

arrays - 多少内存使用具有一个高索引元素的数组?

c# - 我应该使用结构吗?

c - C 中的矩阵乘法返回意外结果