1
votes
 typedef struct structA 
{
   char        C;
   double      D;
   int         I;
} structA_t;
 

Size of this structA_t structure:

sizeof(char) + 7 byte padding + sizeof(double) + sizeof(int) = 1 + 7 + 8 + 4 = 20 bytes

But this is wrong , the correct is

24

. Why?

4
Alignment to 8 byte is possible.user1814023
extra 4 for padding after intRaju Kunde
@RajuKundhe why is that 4 required after int? can you elaborate and put as an answer?gpuguy
Please have a look on Structure Padding and padding.Dayal rai
@gpuguy the word size is 8 Bytes (processor dependent). int is 4 Bytes long (platform dependent), so it must be padded by 4 extra Bytes, the same way sizeof(char)=1 Byte must be padded by 7 BytesH_squared

4 Answers

2
votes

There is most likely 4 byte padding after the last ìnt.

If sizeof(double) == 8 then likely alignof(double) == 8 also on your platform. Consider this situation:

structA_t array[2];

If size would be only 20, then array[1].D would be misaligned (address would be divisible by 4, not 8 which is required alignment).

1
votes

char = 1 byte

double = 8 bytes

int = 4 bytes

align to double =>

padding char => 1+7 

padding double => 8+0

padding int => 4+4

=> 24 bytes

or, simply put, is the multiple of the largest => 3 (the number of fields) * 8 (the size of the largest) = 24

0
votes

my guess would be the size of int in your system is 4 Bytes, so the int must also be padded by 4 Bytes in order to achieve a word size of 8 Bytes.

total_size=sizeof(char) + 7 Byte padding + sizeof(double) + sizeof(int) + 4 Bytes padding = 24 Bytes

0
votes

Good article on padding/alignment: http://www.drdobbs.com/cpp/padding-and-rearranging-structure-member/240007649

Because of the double member it forces everything to be eight byte aligned.

If you want a smaller structure then following structure gives you 16 bytes only!

typedef struct structA 
{
   int         I;
   char        C;
   double      D;
} structA_t;