我试过以下程序:
#include<stdio.h>
typedef struct __attribute__((packed,aligned(8))) Ball {
int size;
int s1;
int s2 __attribute__((packed,aligned(16)));
double q __attribute__((packed,aligned(16)));
} Ball_t;
Ball_t var;
int main()
{
printf("%lu\n",sizeof(Ball_t));
printf("%p %p %p %p\n",&var.size,&var.s1,&var.s2,&var.q);
return 0;
}
Output-
48
0x601060 0x601064 0x601070 0x601080
我原以为输出like-sizeof结构应该是40个字节。 但是,我得到了48个字节。根据我的理解,对齐应该像这样 -
(let suppose start address of structure is 0)
typedef struct __attribute__((packed,aligned(8))) Ball {
int size; // start at 0th and occupy 4 bytes
int s1; //start at 4th and occupy 4 bytes + padding of 8 bytes
int s2 __attribute__((packed,aligned(16))); // starts at 16th byte and occupy 4 bytes +padding 12 bytes
double q __attribute__((packed,aligned(16))); //starts at 32nd and occupy 8 bytes
} Ball_t;
因此,总大小将是4 + 4 + 8 + 4 + 12 + 8 = 40。如果我理解错误,请澄清我。
提前致谢