为什么增加了结构的多个数据成员,而不是单个成员填充? [英] Why is padding added for multiple data members of structures and not for single members?

查看:140
本文介绍了为什么增加了结构的多个数据成员,而不是单个成员填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要填充的概念,只有当有一个结构的多个成员,它为什么时,有一个单一的基本数据类型的成员?包括

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;

有没有填充和sizeofÿ涉及到1个字节。

There is no padding and sizeof Y comes to 1 byte .

如果我们考虑这个结构

struct 
{
    char a;
    int b;
} X;

sizeof的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 成员起始地址 0×05 ,这是不对的。随着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 0×08 ,这是确定。

这篇关于为什么增加了结构的多个数据成员,而不是单个成员填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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