#include <stdio.h>
/*
由于在X86(32位机器)平台下,GCC编译器默认按4字节对齐,
如: 结构体4字节对齐,即结构体成员变量所在的内存地址是4的整数倍
可以通过使用gcc中的__attribute__选项来设置指定的对齐大小。
1):
__attribute__ ((packed)),让所作用的结构体取消在编译过程中的优化对齐,
按照实际占用字节数进行对齐。
2):
__attribute__ ((aligned (n))),让所作用的结构体成员对齐在n字节边界上。
如果结构体中有成员变量的字节长度大于n,则按照最大成员变量的字节长度来对齐。
*/
struct person1 {
char *name;
int age;
char score;
};
struct person2 {
char *name;
int age;
char score;
}__attribute__ ((packed));
struct person3 {
char *name;
int age;
char score;
}__attribute__ ((aligned (4)));
int main()
{
printf("sizeof(char ) = %d\n", sizeof(char));
printf("sizeof(int ) = %d\n", sizeof(int));
printf("sizeof(char * ) = %d\n", sizeof(char *));
printf("sizeof(char **) = %d\n", sizeof(char **));
printf("sizeof(struct person1) = %d\n", sizeof(struct person1));
printf("sizeof(struct person2) = %d\n", sizeof(struct person2));
printf("sizeof(struct person3) = %d\n", sizeof(struct person3));
return 0;
}
上面的代码在32位机器上打印出:
sizeof(char ) = 1
sizeof(int ) = 4
sizeof(char * ) = 4
sizeof(char **) = 4
sizeof(struct person1) = 12
sizeof(struct person2) = 9
sizeof(struct person3) = 12