2009年12月15日 星期二

Structure Arrangement

code:

struct ABC {
int index;
char name[6];
int score;
};

struct DEF{
int att;
char name[3];
};

int main(void)
{
printf("sizeof(ABC) = %d\n", sizeof(struct ABC));
printf("sizeof(DEF) = %d\n", sizeof(struct DEF));
return 0;

}

output:

sizeof(ABC) = 16
sizeof(DEF) = 8

code:

struct ABC {
int index;
char name[6];
int score;
} __attribute__((packed));

struct DEF{
int att;
char name[3];
} __attribute__((packed));

int main(void)
{
printf("sizeof(ABC) = %d\n", sizeof(struct ABC));
printf("sizeof(DEF) = %d\n", sizeof(struct DEF));
return 0;

}

output:

sizeof(ABC) = 14
sizeof(DEF) = 7


A keyword "__attribute__((packed))" that removes all padding.
However, packed structures are slow and inefficient to access. The compiler emulates
unaligned load and store operations by using several aligned accesses with data operations
to merge the results. Only use the __packed keyword where space is far more important
than speed and you can’t reduce padding by rearragement.

沒有留言: