伤心的内存对齐~~~

来源:互联网 发布:单元刚度矩阵 编辑:程序博客网 时间:2024/04/29 21:53
 
/*
*     结构体中的内存对齐
*/
#include <stdio.h>

#pragma pack(4)   //指定按4字节对齐

int main(void)
{
    
struct
 align {
        
struct
 tmp {
            
char
 a;
            unsigned 
short int
 i;
            
char
 b;
        }half;
        
long
 li;
    }ali;

    printf(
"size of struc align is %d ",sizeof
(ali));
    printf(
"size of struc tmp is %d ",sizeof
(ali.half));

    printf(
"size of long is %d ",sizeof(long
));
    printf(
"size of unsigned short int is %d ",sizeof(unsigned short int
));

    
return 0
;

}

 

在align结构体中有两个成员:half和li,其中half为struct tmp类型,一个为long类型。

只有当#pragma 预处理器规定的对齐要求严于struct中最大数据成员字节数时,才按#pragma 指定的字节数对齐。当宽于struc中的要求时,按struct中最大字节成员变量长度来对齐。

这里,在struct align中,首先struct tmp内的成员变量要对齐:1+1  2 1+1  其中+代表填充,+后面的数字代表填充的字节数,这样tmp 占6字节,然后再考虑struct tmp类型的half与long类型的li:6 4+2

所以输出:

size of struc align is 12
size of struc tmp is 6
size of long is 4
size of unsigned short int is 2