结构内存分配,内存分配应为4的倍数 [英] Struct memory allocation, memory allocation should be in multiple of 4

查看:137
本文介绍了结构内存分配,内存分配应为4的倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct x
{
  char b;
  short s;
  char bb;
};


int main()
{
 printf("%d",sizeof(struct x));
}

输出为:6

我在32位编译器上运行此代码.输出应该是8个字节.

I run this code on a 32-bit compiler. the output should be 8 bytes.

我的解释-> 1. Char需要1个字节,下一个short占用2的倍数,因此short创建填充1并占用2个字节,这里已经分配了4个字节.现在,唯一剩下的char成员占用1个字节,但是由于内存分配是4的倍数,因此总内存为8个字节.

My explanation --> 1. Char needs 1 bytes and the next short takes multiple of 2 so short create a padding of 1 and take 2 bytes, here 4 bytes already allocated. Now the only left char member takes 1 byte but as the memory allocates is in multiple of 4 so overall memory gives is 8 bytes.

推荐答案

结构的对齐要求是具有最大对齐方式的成员的对齐要求.此处的最大对齐方式适用于short,因此可能是2.因此,两个b,两个s和两个bb得出6.

The alignment requirement of a struct is that of the member with the maximum alignment. The max alignment here is for short, so probably 2. Hence, two for b, two for s, and two for bb gives 6.

这篇关于结构内存分配,内存分配应为4的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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