Before understanding the byte alignment is assumed that int (4Byte), char (1Byte), short (2Byte)
Understanding byte alignment
Look at the piece of code:
struct Data1 { char a; int b; short c; }; struct Data2 { int a; char b; short c; }; int main() { cout << sizeof(Data1) << endl; cout << sizeof(Data2) << endl; getchar(); return 1; } 输出结果: 12 8
the sizeof (Data1) and the sizeof (Data2) Data1 and Data2 indicate the number of bytes of memory usage, the output is not the same because of Data1 and Data2 compile-time made different byte alignment. Data1 is aligned 4Byte, Data2 is aligned 2Byte.
It assumed that the memory starting address 0x00, the storage model is as follows:
Structure or each member class are aligned memory.
Coding may be used #pragma pack (x) to specify the size of the byte alignment, x n must be a power of 2, otherwise set the size of the byte alignment does not take effect. As the beginning of the code plus #pragma pack (4), both the output 12.
Why byte alignment
First clear: CPU reads the data from the memory starting address is aligned. Following storage memory, cpu 8 bytes read time is required to read two int type. The unaligned very inefficient.
Memory alignment purposes: to allow access to basic types of CPU-time data, so as to enhance the program execution efficiency.