Search code examples
cstructstructure-packing

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?


Solution

  • The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

    For example:

    struct foo_t {
        int x;
        char c;
    };
    

    Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

    Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.