C 结构中的内存对齐

Memory alignment in C-structs(C 结构中的内存对齐)
本文介绍了C 结构中的内存对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)