C 结构体对齐

来源:互联网 发布:星际老男孩淘宝店 整机 编辑:程序博客网 时间:2024/06/05 14:26

在C中,计算结构体的大小不能单纯考虑成员所占字节数,还应该考虑到结构体对齐。

一个例子:

#include <stdio.h>#include <stddef.h>typedef struct _Record{int Num;char Description[21];int Quantity;float Cost_all;}_RECORD;void main(){_RECORD record;printf("sizeof(_RECORD):%d\n", sizeof(record));printf("offsetof(Num):%d\noffsetof(Description):%d\n", offsetof(_RECORD, Num),offsetof(_RECORD,Description));printf("offsetof(Quantity):%d\noffsetof(Cost_all):%d\n",offsetof(_RECORD,Quantity),offsetof(_RECORD,Cost_all));getchar();}

输出结果:

sizeof(_RECORD):36offsetof(Num):0offsetof(Description):4offsetof(Quantity):28offsetof(Cost_all):32
可见,结构体的第一个成员偏移量为0,第二个成员虽然是char类型数组,但是char类型本身只占一个字节,它的前一个成员是整型变量,占4个字节,是char的整数倍,所以偏移量就为4,但是第三个成员又是整型变量,由于前两个成员一共所占字节数为25,所以需要加3来满足边界对齐要求,即有28(4的整数倍)的偏移量。