在C-结构的内存对齐 [英] Memory alignment in C-structs

查看:91
本文介绍了在C-结构的内存对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的32位计算机上,所以我想,内存对齐应该是4个字节。说我有结构:

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

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

真正的大小为6个字节,我想这对齐大小应为8,但的sizeof(MYSTRUCT)返回我6。

但是,如果我写的:

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

真正的大小为10字节,排列为12,这个时间的sizeof(MYSTRUCT)== 12

有人可以解释的区别是什么?

Can somebody explain what is the difference?

推荐答案

至少在大多数机器上,一个类型只会对准一样大类型本身[编辑边界:你真的不能要求任何更多对齐比,因为你必须要能够创建数组,你不能插入填充到一个数组。在您的实现,显然是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个字节pceded $ P $,2字节的填充插入 V3 I ,给予6个字节在 s的数据,两个字节的填充物,并且总共4个字节的 INT 数据的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.

这篇关于在C-结构的内存对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆