|
#include <stdio.h> #include <stdlib.h>
//consider struct aligned
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
struct zlb { char a; //0
int b; //4
short c ; //8
int d; //12
short e;//16
}__attribute__((aligned(8))); //24 ,最后的有效的对齐值应该是 8 (8(指定对齐值) > 4(结构体自身对齐值) ) ,所以 总字节数是 8的倍数 。 可以从下面的结构体来验证, 看看 struct zlb 的放置位置 , 是不是 8 ,便可验证。
struct bob { int a ; // 0
struct zlb zlb_s; // 8
short b; //32
char c; //34
}__attribute__((aligned(16))); //total : 48
//}__attribute__((__packed__));
int main(void) { printf("size of zlb = %d\n",sizeof(struct zlb)); printf("offset a=%d\n",offsetof(struct zlb, a)); printf("offset b=%d\n",offsetof(struct zlb, b)); printf("offset c=%d\n",offsetof(struct zlb, c)); printf("offset d=%d\n",offsetof(struct zlb, d)); printf("offset e=%d\n",offsetof(struct zlb, e)); printf("\n\n");
printf("size of bob struct =%d\n",sizeof(struct bob)); printf("offset a=%d\n",offsetof(struct bob,a)); printf("offset struct zlb=%d\n",offsetof(struct bob, zlb_s)); printf("offset b=%d\n",offsetof(struct bob, b)); printf("offset c=%d\n",offsetof(struct bob, c)); // printf("size of tt struct =%d\n",sizeof(struct tt));
return 0; }
|