首页 > 文章列表 > 为什么在C/C++中,结构体的sizeof不等于每个成员的sizeof之和?

为什么在C/C++中,结构体的sizeof不等于每个成员的sizeof之和?

sizeof 结构体 C/C++
338 2023-09-03

sizeof() 获取的结构类型元素的大小并不总是等于每个单独成员的大小。有时编译器会添加一些填充以避免对齐问题。所以尺寸可能会改变。当结构成员后面跟着一个尺寸较大的成员或位于结构末尾时,将添加填充。不同的编译器有不同类型的对齐约束。在 C 标准中,总对齐结构取决于实现。

情况 1

在这种情况下,双精度 z 为 8 字节长,大于 x(4 字节) )。因此又添加了 4 个字节的填充。此外,短类型数据 y 在内存中具有 2 字节空间,因此添加了额外的 6 字节作为填充。

为什么在C/C++中,结构体的sizeof不等于每个成员的sizeof之和?

示例代码

#include <stdio.h>
struct myStruct {
   int x; //Integer takes 4 bytes, and padding 4 bytes
   double z; //Size of double is 8-byte, no padding
   short int y; //Size of short is 2-byte, padding 6-bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}

输出2

Size of struct: 24

情况 2

在这种情况下,首先插入双精度数,它占用 8 字节的空间。现在添加了整数 x(4 字节)。所以还有另外4个字节的空间。添加短y后,可以将其放入额外的4字节空间中,总共占用16字节空间。

为什么在C/C++中,结构体的sizeof不等于每个成员的sizeof之和?

示例代码

#include <stdio.h>
struct myStruct {
   double z; //Size of double is 8-byte, no padding
   int x; //Integer takes 4 bytes, and padding 4 bytes
   short int y; //Size of short is 2-byte, padding 6-bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}

输出2

Size of struct: 16

情况3

第三种情况也占用16字节的内存空间,但排列方式不同。由于第一个成员是double,所以首先放置,然后添加short 类型数据。现在,当整数尝试插入时,可以将其放入剩余的 6 字节区域中。因此,short 之后存在一个填充,但整数数据之后不需要填充。

为什么在C/C++中,结构体的sizeof不等于每个成员的sizeof之和?

示例代码

#include <stdio.h>
struct myStruct {
   double z; //Size of double is 8-byte, no padding
   short int y; //Size of short is 2-byte, padding 6-bytes
   int x; //Integer takes 4 bytes, and padding 4 bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}

输出2

Size of struct: 16