在Linux环境下,使用GCC编译器时,结构体对齐是一个重要的概念。结构体对齐是指在内存中按照一定的规则对结构体的成员变量进行排列,以提高内存访问的效率。
int
类型通常对齐到4字节边界,double
类型对齐到8字节边界。#include <stdio.h>
// 定义一个结构体
struct Example {
char a; // 1字节
int b; // 4字节
short c; // 2字节
};
// 使用GCC属性指定对齐方式
struct ExampleAligned {
char a;
int b;
short c;
} __attribute__((aligned(8)));
int main() {
struct Example ex;
struct ExampleAligned exAligned;
printf("Size of Example: %zu\n", sizeof(struct Example));
printf("Address of ex.a: %p\n", (void*)&ex.a);
printf("Address of ex.b: %p\n", (void*)&ex.b);
printf("Address of ex.c: %p\n", (void*)&ex.c);
printf("Size of ExampleAligned: %zu\n", sizeof(struct ExampleAligned));
printf("Address of exAligned.a: %p\n", (void*)&exAligned.a);
printf("Address of exAligned.b: %p\n", (void*)&exAligned.b);
printf("Address of exAligned.c: %p\n", (void*)&exAligned.c);
return 0;
}
#pragma pack
指令:#pragma pack
指令:结构体对齐是内存管理中的一个重要方面,合理利用对齐可以提高程序的性能和稳定性。在实际开发中,应根据具体需求选择合适的对齐方式。
领取专属 10元无门槛券
手把手带您无忧上云