c - 如何计算结构成员和填充的大小?

标签 c struct padding

假设我有一个结构为:

struct simple_struct_1
{
  long long a;
  char b;
  long c;
};

a的地址是:0x7ffd415c8b20 b 的地址是:0x7ffd415c8b28 c 的地址是:0x7ffd415c8b30 simple_struct_1 的大小是 24

我已经打印了每个成员的地址和结构的大小,我如何显示这个结构在内存中是如何放置的?就像在 simple_struct_1 中,a 占用 111 个字节并有 222 个填充字节,之后 b 占用 333 个字节,其后有 0 个填充字节,并且c 占用 444 字节,其后填充 555 字节。

最佳答案

您可以使用 offsetofsizeof 获取每个单独字段的详细信息以及整个结构的大小,例如:

printf ("a      is %d@%d\n", sizeof(simple_struct_1.a), offsetof(simple_struct_1, a));
printf ("b      is %d@%d\n", sizeof(simple_struct_1.b), offsetof(simple_struct_1, b));
printf ("c      is %d@%d\n", sizeof(simple_struct_1.c), offsetof(simple_struct_1, c));
printf ("struct is %d@0\n",  sizeof(simple_struct_1));

这应该能让你锻炼:

  • 所有字段的偏移量和大小;
  • 字段之间的间隙;和
  • 最后一个字段之后的间隙(将其偏移量和大小与整个结构的大小相结合。

不要担心在第一个字段之前填充,ISO 标准禁止这样做。

例如,假设您在左侧看到以下输出,右侧显示尺寸和间隙:

a      is 16@0        16 bytes for a long long
                      no gap (0 + 16 = 16, next at 16)
b      is 1@16         1 byte  for a char
                       7 bytes gap (16 + 1 = 17, next at 24)
c      is 8@24         8 bytes for a long
struct is 32@0        no gap at end (24 + 8 = 32, next at 32)

关于c - 如何计算结构成员和填充的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46009855/

相关文章:

c - 使用宏初始化通过引用传递的结构

html - 删除 Blogger 导航栏后删除空白区域(简单模板)

Swift:UIButton edgeinsets 在单元格重绘/滚动后应用

c - 一对变量/结构的偏移量是否相同?

C# 从 byte[] 转换为 struct。字节顺序错误

c - typedef struct 声明错误?

c - Bignum 库,慢素数生成器

html - 将底部填充添加到带有 overflow-y 属性的 div 的最后一个可见元素

c - while循环中的段错误

c - pthread 数组 - 线程是否仍处于事件状态?