默认情况下结构体struct是按最大成员的字节类型对齐的,也就是说有char、int、long 、short 类型,会以long 类型对齐

下面以代码解释:

struct stu{

    char c1;  //1字节

    short a1;  //2字节

    int i1;   //4字节

    long l1;  //8字节,但是在32位系统是4字节

};

printf("size :%zu\n",sizeof(struct stu));

//输出16;是因为char 是占一个字节的,但是它后面的short是2占字节,所以char后面补1位,int 占4字节,而它前面的2个成员变量刚好是占了4个字节,所以紧接着后面写入int类型变量,再后面的long类型是占8字节的,而它前面的所有类型之和也是8的倍数,所以也是紧接着写入long变量。所以输出16

 

struct stu{

    short a1;    //2字节

    int i1;        //4字节

    long l1;     //64位系统是8字节,32位系统是4

    char c1;    //1字节

};

printf("size :%zu\n",sizeof(struct stu));

//输出24;按最大类型对齐

struct stu{

    char c1;  //0x7fff5c90cc00

    int i1;   //0x7fff5c90cc04

    short a1;  //0x7fff5c90cc08

    long l1;  //0x7fff5c90cc10    (16位的地址)

};

printf("size :%zu\n",sizeof(struct stu));

//输出24;按最大类型对齐

 

我们也可以强制使它按我们规定的字节数对齐

#pragma stu(1)  //表示以1字节对齐

struct stu{

    char c1;  //00

    int i1;  //04

    short a1;  //08

    long l1;  //10    (16位的地址)

};

printf("size :%zu\n",sizeof(struct stu));

//输出15;强制以1字节对齐

注:#pragma stu(t)    //t必须是2的指数

 

posted on 2013-12-31 21:08  fooke  阅读(700)  评论(0编辑  收藏  举报