[c] size of struct in C

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

Consider the following C code:

#include <stdio.h>    

struct employee
{
  int id;
  char name[30];  
};

int main()
{
  struct employee e1;      
  printf("%d %d %d", sizeof(e1.id), sizeof(e1.name), sizeof(e1));
  return(0);
}

The output is:

4 30 36

Why is the size of the structure not equal to the sum of the sizes of its individual component variables?

This question is related to c struct structure-packing

The answer is


Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.


Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.


As mentioned, the C compiler will add padding for alignment requirements. These requirements often have to do with the memory subsystem. Some types of computers can only access memory lined up to some 'nice' value, like 4 bytes. This is often the same as the word length. Thus, the C compiler may align fields in your structure to this value to make them easier to access (e.g., 4 byte values should be 4 byte aligned) Further, it may pad the bottom of the structure to line up data which follows the structure. I believe there are other reasons as well. More info can be found at this wikipedia page.