刚才在论坛上又看到有人提出关于内存对齐的问题,又做了一番调查,从中学到一个宏定义:offsetof(<stddef.h>),这个宏可以算出结构体中变量相对结构体首地址的偏移量。根据此,就可以知道内存对齐时,结构体中各个变量实际所占用的内存大小。
typedef struct _AAA{
char ch1;
short int sValue;
char ch2;
int i;
}AAA;
int len = sizeof(AAA);
int sValue_offset = offsetof(AAA,sValue);
int ch2_offset = offsetof(AAA,ch2);
int i_offset = offsetof(AAA,i);
printf("len:%d/n",len); //12
printf("sValue_offset:%d/n",sValue_offset); //2
printf("ch2_offset:%d/n",ch2_offset); //4
printf("i_offset:%d/n",i_offset); //8