为什么在 C/C++ 中,结构体的 sizeof() 结果不等于每个成员 sizeof() 之和?
使用 sizeof() 获取的结构体类型元素的大小并不总是等于每个成员的大小之和。有时编译器会添加一些填充来避免对齐问题。因此大小可能会发生变化。当一个结构体成员后面跟着一个更大尺寸的成员或在结构体的末尾时,就会添加填充。不同的编译器有不同的对齐约束。在 C 标准中,结构体的总对齐取决于实现。
案例 1
在这种情况下,double 类型的 z 长度为 8 字节,大于 x(4 字节)。因此会添加另外 4 字节的填充。此外,short 类型数据 y 在内存中占用 2 字节的空间,因此会添加额外的 6 字节作为填充。

示例代码
#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
在这种情况下,double 类型首先插入,它占用 8 字节的空间。现在添加整数 x(4 字节)。所以还有另外 4 字节的空间。当添加 short 类型的 y 时,它可以放置在额外的 4 字节空间中,并占用总共 16 字节的空间。

示例代码
#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 后面有一个填充,但整数数据后面不需要填充。

示例代码
#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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP