C ++ structure size: 2 + 4 + 2 + 2 + 4 = 16

Possible duplicate:
Why isn & rsquo; t sizeof for a structure equal to the sum of the sizeof of each member?

Why is sizeof();this structure 16 bytes? I am compiling in g ++.

struct bitmapfileheader {       
     unsigned short bfType;
     unsigned int bfSize;
     unsigned short bfReserved1;
     unsigned short bfReserved2;
     unsigned int bfOffBits;   
   };
+3
source share
9 answers

This is because 4 byte ints are aligned on a 4 byte boundary, so after bfType there are 2 padding bytes.

+12
source

Alignment. On your platform, probably, ints should be aligned by 4 bytes, and shorts aligned by 2 bytes.

+0 -1 : bfType
+2 -3 : <padding>
+4 -7: bfSize
+8 -9: bfReserve1
+10 -11: bfReserve2
+12 -15: bfOffBits
-------------
16 bytes

Alignment is good because custom structures require additional work for many architectures.

+8

. , .

, UNALIGNED.

+7

, 4- .

+5

- , . , , ( , ). n- , n - . . , . ( ) - , - , , . , int , , int .

bfType, , 2- , bfSize, , 4- . 4 2 bfType bfSize.

, , , , ABI ( , , ). 5 , 16 , .

, . , , , , . .

+2

U ,

+1

ISO ++ 03, 9.2 [class.mem]/12:

() , , , . , , (11.1). , ; (10.3) (10.1).

+1

- , ,

0
source

This is due to alignment - the compiler needs to do some debugging.

0
source

Source: https://habr.com/ru/post/1725207/


All Articles