Today encountered a problem, the use of data transmission data in the resolution of data dislocation, think for a long time, found to be #pragma pack (n) trouble.
First, the parser uses the compile byte setting, but when the sender does not use it, the same structure is used to parse the data, and two bytes are occupied by 0. Later unified use, problem solving.
struct struct: When not using #pragma pack (1), after parsing remotport is no problem, and then parse Remotip, the first two bits of IP address after byte conversion is 0.0.x.x because Word is not enough 4 bytes, The compiler fills in the 0 placeholder automatically.
This is the parameter setting for the compiler, for the structure byte alignment setting, #pragma pack is the alignment of the specified data in memory.
#pragma pack (n) Action: The C compiler will be aligned by N bytes.
#pragma pack () Effect: cancels custom byte alignment.
#pragma pack (push,1) function: means to set the original alignment of the stack, and set a new alignment to a byte alignment
#pragma pack (POP) Action: Restore Alignment State
As a result, adding push and pop allows alignment to revert to its original state, rather than the compiler default, which can be said to be better, but many times the difference is small
Such as:
#pragma pack (push)//Save alignment status
#pragma pack (4)//set to 4-byte alignment
Equivalent to #pragma pack (push,4)
#pragma pack (1)
Action: Adjusts the bounds of the structure to align with one byte;< to align the structure in 1-byte alignment >
However, if you change the order of the DWORD and word in the struct, the results are different. As follows:
#pragma pack (n) Trouble