C 结构中的内存对齐

我在 32 位机器上工作,所以我想内存对齐应该是 4 个字节.假设我有这个结构:

I'm working on a 32-bit machine, so I suppose that the memory alignment should be 4 bytes. Say I have this struct:

typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
} myStruct;

普通添加的大小是 6 个字节,我想对齐的大小应该是 8,但是 sizeof(myStruct) 返回我 6.

The plain added size is 6 bytes, and I suppose that the aligned size should be 8, but sizeof(myStruct) returns me 6.

但是如果我写:

typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
    int i;
} myStruct;

普通添加的大小是10个字节,对齐的大小应该是12,这次sizeof(myStruct) == 12.

the plain added size is 10 bytes, aligned size shall be 12, and this time sizeof(myStruct) == 12.

有人能解释一下有什么区别吗?

Can somebody explain what is the difference?

推荐答案

至少在大多数机器上,类型只与类型本身一样大的边界对齐.在您的实现中,short 显然是 2 个字节,而 int 是 4 个字节.

At least on most machines, a type is only ever aligned to a boundary as large as the type itself . On your implementation, short is apparently 2 bytes, and int 4 bytes.

这意味着您的第一个结构与 2 字节边界对齐.由于所有成员各占2个字节,因此它们之间没有插入填充.

That means your first struct is aligned to a 2-byte boundary. Since all the members are 2 bytes apiece, no padding is inserted between them.

第二个包含一个 4 字节的项目,它与 4 字节的边界对齐.由于前面是6个字节,所以在v3i之间插入了2个字节的padding,在shorts中给出了6个字节的数据,两个填充字节,以及 int 中另外 4 个字节的数据,总共 12 个.

The second contains a 4-byte item, which gets aligned to a 4-byte boundary. Since it's preceded by 6 bytes, 2 bytes of padding is inserted between v3 and i, giving 6 bytes of data in the shorts, two bytes of padding, and 4 more bytes of data in the int for a total of 12.

相关文章