为什么这个结构体的大小是24 ?

Why is the size of this struct 24?

本文关键字:结构体 为什么      更新时间:2023-10-16

我有一个结构体,我想计算它的大小:

#pragma pack(push,4)
struct  MyStruct
{  
    uint32_t i1;    /* size=4, offset=0. */
    uint32_t i2;    /* size =4 offset =4 */
    uint16_t s1;    /* size =2 offset=8 */
    unsigned char c[8]; /* size=8 offset=12*/
    uint16_t s2;    /* size=2 offset=20. */
    uint16_t s3;    /* size=2 offset=24. */
} ; // total size is 26 
static_assert(sizeof(MyStruct) == 24, "size of MyStruct incorrect");
#pragma pack(pop)

静态断言显示大小为24,但我的计算显示它应该是26。

为什么是24码?

我正在使用visual studio 2012开发windows 7, 32位应用程序

uint16_t的对齐只有2,因此偏移量为:

#pragma pack(push,4)
struct  MyStruct
{  
    uint32_t i1;        /* offset=0  size=4 */
    uint32_t i2;        /* offset=4  size=4 */
    uint16_t s1;        /* offset=8  size=2 */
    unsigned char c[8]; /* offset=10 size=8 */
    uint16_t s2;        /* offset=18 size=2 */
    uint16_t s3;        /* offset=20 size=2 */
                        /* offset=22 padding=2 (needed to align MyStruct) */
} ; // total size is 24

编辑为了确保

的所有元素
MyStruct A[10]; // or
MyStruct*B = new MyStruct[10];

正确对齐。这要求sizeof(MyStruct)alignof(MyStruct)的倍数。这里,sizeof(MyStruct) =6* alignof(MyStruct) .

任何struct/class类型总是填充到其对齐的下一个倍数。

除了沃尔特的答案,考虑自己抓这条鱼。您所需要的只是printf函数和简单的算术:

  struct MyStruct ms;
  printf("sizeof(ms): %zdn", sizeof(ms));
  printf("i1t%tdn", (uint8_t*)&ms.i1 - (uint8_t*)&ms);
  printf("i2t%tdn", (uint8_t*)&ms.i2 - (uint8_t*)&ms);
  printf("s1t%tdn", (uint8_t*)&ms.s1 - (uint8_t*)&ms);
  printf("c t%tdn", (uint8_t*)&ms.c  - (uint8_t*)&ms);
  printf("s2t%tdn", (uint8_t*)&ms.s2 - (uint8_t*)&ms);
  printf("s3t%tdn", (uint8_t*)&ms.s3 - (uint8_t*)&ms);

(%zd用于打印size_t, %td用于打印ptrdiff_t)一个普通的%d可能会在大多数系统上工作得很好。

输出:

sizeof(ms): 24
i1      0
i2      4
s1      8
c       10
s2      18
s3      20

4 4 2 8 2 2 -将包装为:

4 4 4 8 2 2 -最后两个组合在一起为4字节。第三项需要填充,最后一项和前一项不需要。