views:

87

answers:

2

Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?

#include <stdio.h>

int main(){

struct word1{
 char a;
 int b;
 char c;
};

struct word2{
 char a;
 char b;
 int c;
};

printf("%d\t%d\n", sizeof(int), sizeof(char));   //Output : 4 1
printf("%d\t%d\n", sizeof(struct word1), sizeof(struct word2)); //Output: 12 8
return 0;
}

The code is available at IDEONE.

Why is the size of struct 1 (word1) greater than the size of struct 2 (word2)?

Is this a compiler problem?

+9  A: 

The int probably has a four-byte alignment requirement, so in the first case, both of the char elements need to have three padding bytes appended to them but in the second case you only need two padding bytes after the second char element (because a char element has an alignment of one byte).

word1 looks like:

0   |1   |2   |3   |4   |5   |6   |7   |8   |9   |10  |11
a   |  (padding)   |b                  |c   |  (padding)

word2 looks like:

0   |1   |2   |3   |4   |5   |6   |7
a   |b   |(padding)|c               
James McNellis
+5  A: 

Case 1:

  0    1    2    3    4  
+---------------------+
| a    | Unused       |      4 bytes
+---------------------+

  0    1    2    3    4 
+---------------------+
|       b             |      4 bytes
+---------------------+

  0    1    2    3    4 
+---------------------+ 
| c    | Unused       |      4 bytes
+---------------------+

Total : 12

Case 2:

  0    1    2    3    4 
+---------------------+
| a   | b   | Unused  |      4 bytes
+---------------------+

  0    1    2    3    4 
+---------------------+
|       c             |      4 bytes
+---------------------+

Total : 8

P.S : Structure Padding is implementation defined.

Prasoon Saurav