sizeof(),C结构中的对齐方式:

前端之家收集整理的这篇文章主要介绍了sizeof(),C结构中的对齐方式:前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
前言:
我的研究结构对齐.看了 this问题,this一个和 this一个 – 但仍然没有找到我的答案.

我的实际问题:

这是我创建的代码片段,以澄清我的问题:

  1. #include "stdafx.h"
  2. #include <stdio.h>
  3.  
  4. struct IntAndCharStruct
  5. {
  6. int a;
  7. char b;
  8. };
  9.  
  10. struct IntAndDoubleStruct
  11. {
  12. int a;
  13. double d;
  14. };
  15.  
  16. struct IntFloatandDoubleStruct
  17. {
  18. int a;
  19. float c;
  20. double d;
  21. };
  22.  
  23. int main()
  24. {
  25. printf("Int: %d\n",sizeof(int));
  26. printf("Float: %d\n",sizeof(float));
  27. printf("Char: %d\n",sizeof(char));
  28. printf("Double: %d\n",sizeof(double));
  29. printf("IntAndCharStruct: %d\n",sizeof(IntAndCharStruct));
  30. printf("IntAndDoubleStruct: %d\n",sizeof(IntAndDoubleStruct));
  31. printf("IntFloatandDoubleStruct: %d\n",sizeof(IntFloatandDoubleStruct));
  32. getchar();
  33. }

它的输出是:

  1. Int: 4
  2. Float: 4
  3. Char: 1
  4. Double: 8
  5. IntAndCharStruct: 8
  6. IntAndDoubleStruct: 16
  7. IntFloatandDoubleStruct: 16

我在IntAndCharStruct和IntAndDoubleStruct中看到了对齐.

但我只是没有获得IntFloatandDoubleStruct.

简单地说:为什么sizeof(IntFloatandDoubleStruct)= 24?

提前致谢!

p.s:我正在使用Visual-Studio 2017标准控制台应用程序.

编辑:
根据评论,测试了IntDoubleAndFloatStruct(元素的不同顺序)并且在sizeof()中得到了24 – 如果答案会注意并解释这个案例,我将很高兴.

解决方法

你的结构必须是8 * N字节长,因为它有一个8字节(双)的成员.这意味着结构位于存储器中的地址(A)可被8整除(A%8 == 0),其结束地址将是(A 8N),也可以被8整除.

从那里,您存储2个4字节变量(int float),这意味着您现在占用内存区域[A,A 8].现在存储一个8字节的变量(双精度).因为(A 8)%8 == 0 [因为A%8 == 0],所以不需要填充.因此,没有填充,你得到4 4 8 == 16.

如果您将订单更改为int – >双 – >浮动你将占用24个字节,因为双变量原始地址不能被8整除,并且它必须填充4个字节才能到达有效地址(并且结构在末尾也会有填充).

  1. |--------||--------||--------||--------||--------||--------||--------||--------|
  2. | each || cell || here ||represen||-ts 4 || bytes || || |
  3. |--------||--------||--------||--------||--------||--------||--------||--------|
  4.  
  5. A A+4 A+8 A+12 A+16 A+20 A+24 [addresses]
  6. |--------||--------||--------||--------||--------||--------||--------||--------|
  7. | int || float || double || double || || || || | [content - basic case]
  8. |--------||--------||--------||--------||--------||--------||--------||--------|
  9.  
  10. first padding to ensure the double sits on address that is divisble by 8
  11. last padding to ensure the struct size is divisble by the largest member's size (8)
  12. |--------||--------||--------||--------||--------||--------||--------||--------|
  13. | int || padding|| double || double || float || padding|| || | [content - change order case]
  14. |--------||--------||--------||--------||--------||--------||--------||--------|

猜你在找的C&C++相关文章