0

What is the size (sizeof(How_Many_Bytes)) of the following structure, given the following machine parameters:

sizeof(char) == 1; sizeof(int) == 4; sizeof(long) == 8; sizeof(char *) == 8; 

Integer values must be aligned.

typedef struct how_many_bytes { 
 long s; 
 char c, e; 
 int i; 
 char *d; 
} How_Many_Bytes; 

I thought it would be 4+1+1+(2+4)+8 = 20 bytes but when I run on my machine I get 24 bytes. I wonder why?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ivesingh
  • 31
  • 1
  • 2
  • 3

1 Answers1

2

Conceptually, what happens is this:

typedef struct how_many_bytes { 
 long s;          // 8   (NOT 4!)
 char c, e;       // 2
 char pad1, pad2; // 2 note these
 int i;           // 4 
 char *d;         // 8
} How_Many_Bytes; // 24 total

Some types have alignment requirements. Often on 4 or 8 byte boundaries. So what the compiler does is to make the fields align on these boundaries by added unnamed empty fields.

Charlie Burns
  • 6,994
  • 20
  • 29