# Thread: Why sizeof() this struct is 12 ?

1. ## Why sizeof() this struct is 12 ?

Code:
```struct st{
char c;
int i;
short s;
};
int main(){
cout<<sizeof(st)<<endl;
}```
Why the size is 12, not 8 or 7?

3. In my MS Visual Studio it's 12.
I can understand 8, but how come 12?

Originally Posted by cyberfish

4. I get 12.

I suspect the c starts off on a 4-byte word boundary.

Then, the int causes 3 pad bytes to be skipped in order to maintain a proper word boundary. That's 8 bytes so far.

Then, the short gets 2 bytes, and the whole structure is most likely also padded out to a full word.
Code:
```#include <stdio.h>
#include <stddef.h>

struct st{
char c;
int i;
short s;
};

int main(){
printf("&#37;d\n", sizeof(struct st) ) ;
printf("%d\n", offsetof(struct st,c) ) ;
printf("%d\n", offsetof(struct st,i) ) ;
printf("%d\n", offsetof(struct st,s) ) ;
return 0 ;
}```
Output:
Code:
```[Session started at 2008-04-08 00:02:17 -0500.]
12
0
4
8```

5. The standard says the compiler can pad for any reason. Asking why the size is some particular value is fruitless, because the answer is officially, "Because."

6. try changing your struct to:
Code:
```struct st
{
int i;
short s;
char c;
};```

7. An int (being 4 bytes long) needs to be aligned to 4 byte boundaries (at least for efficiency, and in some machines to avoid traps/faults):
so your variable i is aligned to 4 bytes by padding 3 bytes after c. This makes 8 bytes so far.

s is a short, so it takes up 2 bytes. This makes 10 bytes.

But now we have the problem that if we make an array of struct st, the next instance of i will not be on an even boundary of 4, so the struct needs to be further aligned to match up with a int. This takes it out to 12 bytes. It would make no sense to align the int part to 4 bytes within the struct if an array of structs isn't also aligned such that the int part is aligned in every instance of such an array, right?

As manav suggests, start with the biggest items, then smaller, and you won't get (as much) padding - it will still need to be aligned to match the biggest aligned item (4 bytes in this case), but the size now becomes 8.

--
Mats