为什么2字节对齐比较短? [英] Why short is 2-byte aligned?

查看:153
本文介绍了为什么2字节对齐比较短?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C结构的声明:

struct align
{
    char c; //1 byte
    short s;//2 bytes
};

在我的环境中,sizeof(struct align)为4,填充1个字节介于'char c '和'short s'。有人说这是因为短必须对齐2个字节,因此在字符c之后填充1个字节。在32位计算机上,我知道'int'最好对齐4个字节,以防止2个内存读取周期,因为在CPU和内存之间的地址总线上发送的地址是4的倍数。但是'short'是2个字节,这要少一些多于4个字节,因此其地址可以是4字节单位内的任何字节(最后一个字节除外)。

On my environment, sizeof(struct align) is 4 and the padding 1 byte is between 'char c' and 'short s'. Some say that's because `short' has to be 2-byte aligned, so pading 1 byte is after 'char c'. On 32-bit machine, I know 'int' better be 4-byte aligned to prevent 2 memory read cycles since addresses sent on address bus between CPU and memory is a multiple of 4. But 'short' is 2 bytes, which is less than 4 bytes, so its address could be any byte within a 4-byte unit (except last byte).

4个地址的倍数-> | 0 | 1 | 2 | 3 |

multiple of 4 address -> |0|1|2|3|

我的意思是,短'可以从0、1或2开始。可以通过1个读取周期来检索所有数据,而不必从0或2检索。在我的结构对齐情况下, char c可以为0, short s可能是1-2,填充可能是3。

I mean, 'short' can start at 0, 1, or 2. All can be retrieved by 1 read cycle, doesn't have to 0 or 2. In my 'struct align' case, 'char c' could be at 0, 'short s' could be at 1-2, padding could be at 3.

为什么2字节长的 short必须对齐2字节?

Why 2-byte long "short" has to be 2-byte aligned?

谢谢

更新我的环境:
gcc版本4.4.7,i686,Intel

Update my environment: gcc version 4.4.7, i686, Intel

推荐答案

这是因为 struct 的成员与该类型的单个变量没有区别,机器的角度。

That is because a member of a struct is no difference from a single variable of that type, from the machine's perspective. Whatever alignment you choose, it applies to both.

例如,如果 short 是两字节长,

For example, if short is two-byte long,

struct align
{
    char c;
    short s; // two-byte word
};

short ss; // two-byte word

成员 s 是2字节类型(例如IA32中的WORD ),与独立变量 ss 的类型完全相同。底层架构将它们视为相同。因此,当涉及该类型的对齐要求时,它仅适用于这两种类型。

The member s is of 2-byte type (e.g. WORD in IA32), exactly the same type of a "standalone" variable ss. The underlying architecture regards them as the same. So when there comes to an alignment requirement for that type, it just applies to both.

如果在数据末尾添加填充,则可能仍然错位。考虑 ss 的开头是4字节边界的结尾。

And if you add the padding at the end of the data, it may still be misaligned. Consider the start of ss is at the end of a 4-byte boundary.

这篇关于为什么2字节对齐比较短?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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