为什么为结构的多个数据成员而不是单个成员添加填充? [英] Why is padding added for multiple data members of structures and not for single members?
问题描述
为什么只有一个结构有多个成员时才添加填充的概念,为什么只有一个基本数据类型成员时不包含填充的概念?
Why the concept of padding is added only when there are multiple members of a structure and why is it not included when there is a single basic data type member ?
如果我们考虑在 32 位机器上
if we consider on a 32bit machine
struct
{
char a;
} Y;
没有填充并且 Y 的 sizeof 达到 1 字节.
There is no padding and sizeof Y comes to 1 byte .
如果我们考虑这个结构
struct
{
char a;
int b;
} X;
X 的大小为 8 字节.
Sizeof X will be 8bytes .
我的问题是为什么在第二种情况下要添加填充?如果它是为了机器的高效访问,通常以 4 字节的倍数块读取数据,那么为什么在第一种情况下没有填充?
My question is Why was padding adding in the second case ? If it is for efficient access by the machine which normally reads data in blocks of multiples of 4bytes then why was there no padding in the first case ?
推荐答案
在第二种情况下添加了填充,因为在您的机器上,int
对齐到 4 个字节.所以它必须驻留在可以被 4 整除的地址.
Padding is added in the second case because, on your machine, an int
is aligned to 4 bytes. So it has to reside at an address that is divisible to 4.
0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B
a b b b b
如果不添加填充,则int
成员从地址0x05
开始,这是错误的.添加了 3 个填充字节:
If no padding is added, the int
member starts at address 0x05
, which is wrong. With 3 added padding bytes:
0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B
a | padding | b b b b
现在int
在0x08
,没问题.
这篇关于为什么为结构的多个数据成员而不是单个成员添加填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!