Byte alignment

VC provides # pragma pack (n) to set the variable to n-byte alignment (n must be 0 or a power of 2). If n is 0 or is omitted, alignment uses the default alignment values.

There are two cases to n-byte-aligned starting address offset:

Case one:  if n is greater or equal to than the number of bytes which structure variable occupied, the offset must meet the default alignment. The structure size is the multiple of the max variable size. 

#pragma pack(push)

#pragma pack(8) //n = 8

struct s{

    int a; //4            //4

    char b; //1          //1  ==> 2 need pad 1 for c

    unsigned short c; //2

};

#pragma pack(pop)

Step1: because n=16 > max sizeof(int) = 4, so the structure will be aligned by 4 byte, the variable a is saved from the 0th byte;

Step 2: the variable b is saved 4th byte which is the multiple of 4, so not need complement;

Step 3: when the variable c is saved, it need align by 2 bytes, so pad 1 byte;

sizeof (s) = 8

 

 Case two: if n is less than the size of structure’s variable (the max one), the offset is the multiple of n; The structure size is the multiple of n. 

#pragma pack(push)

#pragma pack(2)  //n=2

struct s{

    char b; //1     ==>  2

    int a; //4         ==> 4

    //unsigned short c; //2  ==>  2

};

#pragma pack(pop)

sizeof (s) = 8 

some Examples:

(1) n=4 > max variable size 2, so is the CASE ONE:

#pragma pack(push)

#pragma pack(4) //n=4

struct s{

    char b; //1  => 2  need pad 1 for c

    unsigned short c; //2

};

#pragma pack(pop)

sizeof (s) = 4

(2) n=4 = max variable size 4, so is the CASE ONE:

#pragma pack(push)

#pragma pack(4) //n=4

struct s{

    char b; //1  => 4 need pad 3 for a

    int a; //4

    unsigned short c; //2

};  //10B  => 12B The structure size need be the multiple of int(4)

#pragma pack(pop)

sizeof (s) = 12 

(3) n=4 < max variable size 8, so is the CASE TWO:

#pragma pack(push)

#pragma pack(4)  //n=4

 struct s {

   char a;     //1   =>  4 need pad 3 for aligning by n

   double b;   //8   =>  8

   int  c;     //4   =>  4

}; //16 is the multiple of n

#pragma pack(pop)

sizeof (s) = 16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值