0

I have a structure and I wrote the following code to print the size of the structure. I get "8" as the size of structure though I was expecting "6" . sizeof(int)+sizeof(char)+sizeof(char) = 4+1+1 = 6. And If I comment the int part of structure I get the desirable result (i.e size of structure as 2)

I also printed out the size of int which is coming 4.

typedef struct example
{
    int one;      
    char two;
    char three;
}example;

int main()
{
    printf("value %d %d ",sizeof(example),sizeof(int));
}
user968000
  • 1,765
  • 3
  • 22
  • 31
  • This is due to alignment, your struct is being 4-byte aligned. http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member – wkl May 03 '13 at 16:47
  • So you can safely put the structure in an array and the `int` member will be correctly aligned. – Bill May 03 '13 at 16:50

4 Answers4

4

The compiler will some times add in padding to make using the struct more efficient.

Ryan Erb
  • 828
  • 1
  • 8
  • 28
2

Imagine an array of struct example.

Each entry in the array must be sizeof(struct example) bytes.

An int, however, must always be 4-byte aligned. 6 bytes can't do that, so the compiler rounds the size up to 8. Now each int in your array is aligned.

ams
  • 24,923
  • 4
  • 54
  • 75
1

It's because of the structure alignment and padding.

zakinster
  • 10,508
  • 1
  • 41
  • 52
0

This is probably because, on many architectures, most compilers insert additional padding into structures to aid in proper alignment. In this case, it looks like the structure is being padded to an even multiple of word-sized values. On a 32-bit processor, the word size is 4 bytes.

Matt Patenaude
  • 4,497
  • 1
  • 22
  • 21