Memory alignment in C-structs(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个字节,所以在v3
和i
之间插入了2个字节的padding,在short
s中给出了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 short
s, two bytes of padding, and 4 more bytes of data in the int
for a total of 12.
这篇关于C 结构中的内存对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C 结构中的内存对齐
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01