Question about the length of the structure - causing data loss

Regarding offsets :

1. The address offset of a member in a structure variable is the offset of the previous member plus the size of a member .
2. The size of the structure is equal to the offset of the last member plus the size of the last member.

About storage variable address alignment

The compiler will follow two principles when compiling the program:
1. The offset of the member in the structure variable must be an integer multiple of the member size (0 is considered an integer multiple of any number) 2. The
structure size must be all members Integer multiples of the size.

Example:
  struct ssd
  {   float a; address offset 0 (first address)   int b; address offset 4 (0+4)   char c; address offset 8 (4+4)   char d; address offset 9(8+1)   float e; address offset 10(9+1)   }; answer:   principle 1: not satisfied, e address offset 10 is not an integer multiple of member size (4)   principle 2: not satisfied, The size of the structure is 14, which is not an integer multiple of the size of all members (4/1).   Therefore: the compiler will automatically add 2 empty bytes to e,   that is, float e; address offset 12 (9+1+2)   Principle 1: Satisfied, e address offset 12 is an integer multiple of the member size (4)   Principle 2: Satisfied, the structure size is 16 is an integer multiple of all member sizes (4/1) Summary: Pay attention to the structure when calculating the length of the structure Data alignment requirements between members, if calculated simply according to the size of the structure members will cause data loss.













  

Reference: https://blog.csdn.net/jueduiwudi6/article/details/80721108?utm_medium=distribute.pc_relevant.none-task-blog-2 default baidujs_utm_term~default-0.no_search_link&spm=1001.2101.3001.4242.1

Guess you like

Origin blog.csdn.net/weixin_49048045/article/details/120991144