字节对齐是指在计算机内存中,数据按照一定的规则进行排列,以提高CPU访问数据的效率。结构体字节对齐是指编译器在编译时自动为结构体成员分配内存时,按照一定的规则进行对齐,使得每个成员的起始地址是其自身大小的整数倍。
#include <stdio.h>
// 默认情况下,结构体会进行自然对齐
struct Example {
char a; // 1 byte
int b; // 4 bytes
short c; // 2 bytes
};
// 使用 __attribute__((packed)) 取消对齐
struct PackedExample {
char a; // 1 byte
int b; // 4 bytes
short c; // 2 bytes
} __attribute__((packed));
int main() {
printf("Size of struct Example: %zu\n", sizeof(struct Example)); // 输出 12
printf("Size of struct PackedExample: %zu\n", sizeof(struct PackedExample)); // 输出 7
return 0;
}
问题:结构体大小不符合预期,导致内存浪费或访问错误。
原因:
解决方法:
__attribute__((packed))
取消对齐:__attribute__((packed))
取消对齐:alignas
关键字:alignas
关键字:通过这些方法,可以灵活控制结构体的字节对齐,确保程序的正确性和性能优化。
领取专属 10元无门槛券
手把手带您无忧上云