计算结构尺寸 [英] calculating the size of structure

查看:77
本文介绍了计算结构尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我发现这个struct ...

I was going through the concept of structure member alignment and structure padding concept when I found that the size of this struct ...

struct node{
  int b;
  char a;
 };

...是8个字节(即,它包含3个填充字节),而此struct ...

... is 8 bytes (i.e. it contains 3 bytes of padding) whereas the size of this struct ...

struct node{
  char a;
};

...仅1个字节.为什么后者没有填充?

... is only 1 byte. Why is there no padding in the latter?

推荐答案

记住这两个填充规则:

  1. 仅当结构成员紧随要求更大对齐或在结构末端的成员时才插入填充.
  2. 最后一个成员用所需的字节数填充,因此结构的总大小应为任何结构成员最大对齐方式的倍数.
  1. Padding is only inserted when a structure member is followed by a member with a larger alignment requirement or at the end of the structure.
  2. The last member is padded with the number of bytes required so that the total size of the structure should be a multiple of the largest alignment of any structure member.

在第二个结构中的

成员a后面没有任何具有较大对齐方式的成员,也是最大的对齐成员,这意味着-无填充.

Member a in second structure is not followed by any member or member with larger alignment and it is also the largest alignment member which means--No Padding.

阅读此答案以获取更多详细说明.

Read this answer for more detailed explanation.

这篇关于计算结构尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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