考虑:
struct mystruct_A
{
char a;
int b;
char c;
} x;
struct mystruct_B
{
int b;
char a;
} y;
结构的大小分别为 12 和 8。
这些结构是填充的还是包装的?
什么时候进行填充或打包?
最佳答案
填充 aligns结构成员到“自然”地址边界 - 例如,int
成员将具有偏移量,在 32 位平台上为 mod(4) == 0
。默认情况下,填充处于启用状态。它将以下“间隙”插入到您的第一个结构中:
struct mystruct_A {
char a;
char gap_0[3]; /* inserted by compiler: for alignment of b */
int b;
char c;
char gap_1[3]; /* -"-: for alignment of the whole struct in an array */
} x;
另一方面,打包会阻止编译器进行填充 - 这必须明确请求 - 在 GCC 下它是 __attribute__((__packed__))
,因此如下:
struct __attribute__((__packed__)) mystruct_A {
char a;
int b;
char c;
};
将在 32 位架构上生成大小为 6
的结构。
但需要注意的是,未对齐的内存访问在允许的架构(如 x86 和 amd64)上速度较慢,并且在 SPARC 等严格对齐架构上被明确禁止。
关于c - 结构填充和包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47950230/