为什么填充没有在这种情况下发生? [英] why padding is not happening in this case?

查看:133
本文介绍了为什么填充没有在这种情况下发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按我的知识,默认4字节对齐就搞定。说

As per my knowledge, By default 4-byte alignment will be done. say

typedef struct
{
     int data7;  
     unsigned char data8;
     //3 -bytes will be added here.
}Sample1;

所以的sizeof(样品1)将是8。

但对于以下结构,填充为什么没有发生?

But for the following structure, why padding is not happened?.

typedef struct
{
     unsigned char data1;
     unsigned char data2;
     unsigned char data3;
     unsigned char data4;
     unsigned char data5;
     unsigned char data6;

}Sample2;

不过的sizeof(样品2)仅为6。此样品2不是一个4字节对齐的结构?

But the sizeof(Sample2) is 6 only. This Sample2 is not a 4 byte aligned structure?

编辑:

根据维基

数据对准装置将在一个存储器偏移量等于字的大小,从而增加了系统的性能的某个倍数的数据由于CPU处理存储器的方式。

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

但样品2的成员不会在倍数对齐两个右??

But members of Sample2 will not be aligned in multiples of two right??

感谢。

推荐答案

在你的第二个结构中的字段均需要4字节对齐。 unsigned char型只需要1字节对齐。因此,没有必要实际它对齐的4个字节。

None of the fields in your second struct require 4-byte alignment. unsigned char only needs 1-byte alignment. Therefore, there is no need to actually align it to 4 bytes.

结构体一般只对准所有字段的最大对齐

Structs are generally only aligned to the maximum alignment of all the fields.

这篇关于为什么填充没有在这种情况下发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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