To make CPU access data more efficient, the compiler automatically performs alignment operations during program compilation (4-byte alignment by default for GCC and 8-byte alignment for windows VC ), the so-called alignment means that the first address of the data is an integer multiple of the Data Length. If the length of the int is 4, the first address should be divisible by 4.
# Include <stdio. h> pack (4) // set 4-byte alignment pack () // restore the default alignment of the compiler main (,(
Running result
#./
Result Analysis:
The longest element in the test_struc struct is sizeof (short) = 2 bytes,
Char a ------------ 2 bytes
Short B ----------- 2 bytes
Char c ------------ 2 bytes
# Include <stdio. h> main (,(
Running result:
#./
Result Analysis:
_ Attribute _ (aligned (4) is forced to 4-byte aligned. No matter the maximum size of the elements in the struct, the overall size of the struct must be an integer multiple of 4.
Char a -------------- 2 bytes
Short B ------------- 2 bytes
Char c --------------- 4 bytes