0

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

Here is the code:

#include <stdio.h>

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

void main(){
  printf("The size of int is: %d\n",(int)sizeof(int));
  printf("The size of char is: %d\n",(int)sizeof(char));
  printf("The size of small is: %d\n",(int)sizeof(struct small));
}

Here is the output:

The size of int is: 4
The size of char is: 1
The size of small is: 12

I expect the size of small to be 9,but it turns out to be 12

Community
  • 1
  • 1
sliter
  • 1,063
  • 1
  • 17
  • 34
  • 5
    Your expectations are simply wrong. Nobody said that the size of the struct would be the sum of the sizes of its members. – Kerrek SB Mar 04 '12 at 22:25
  • 5
    It's because of alignment constraints. It has been asked hundreds of times here, on SO. – Coren Mar 04 '12 at 22:25
  • To add to the above comments, look into 'offsetof' macro in stddef.h. It evaluates the offset (in bytes) of a given member within a structure – pmohandas Mar 04 '12 at 22:31

1 Answers1

1

It's because of alignment requirements. If you were to declare an array of struct smalls:

struct small arr[10];

then each element's a would be immediately after the preceding element. On your system, apparently, ints need to be aligned to four-byte boundaries — either as an absolute requirement, or simply for optimal performance — so struct small includes three bytes of padding to ensure that a subsequent struct small's a is aligned properly.

ruakh
  • 175,680
  • 26
  • 273
  • 307