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