# Pragma pack (n) tells the compiler that the byte alignment mode is n Bytes alignment. n Bytes alignment means that there are two types of offsets for the starting address of the variable: first, if n is greater than or equal to the number of bytes occupied by the variable, the offset must satisfy the default alignment. Second, if n is less than the number of bytes occupied by the type of the variable, if the offset is a multiple of N, the default alignment is not required. The total size of the structure also has a constraint, which is divided into the following two cases: if n is greater than the number of bytes occupied by all member variable types, the total size of the structure must be a multiple of the space occupied by the largest variable; otherwise, it must be a multiple of N.
For example
# Pragma pack (2)
Union u
{
Char Buf [13];
Int I;
};
Enum color {red, blue, yellow };
Struct t
{
Int I;
Union u;
Color C;
};
Sizeof (struct T) = 22
If # pragma pack (4), sizeof (struct T) = 24.
You can also use push and pop for default recovery.
# Pragma pack (push)
# Pragma pack (2)
...
# Pragma pack (POP)
Note: Generally, N takes only 1, 2, 4, and so on. the compiler should automatically convert n to a value close to the above value.
Original article: http://blog.csdn.net/hongchangfirst/article/details/8886269
Author: hongchangfirst
Hongchangfirst home: http://blog.csdn.net/hongchangfirst