Why the size is 12, not 8 or 7?Code:struct st{ char c; int i; short s; }; int main(){ cout<<sizeof(st)<<endl; }
Why the size is 12, not 8 or 7?Code:struct st{ char c; int i; short s; }; int main(){ cout<<sizeof(st)<<endl; }
on my GCC/Linux 32-bit it's 8. I am guessing it's the compiler aligning addresses (adding padding to your struct).
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.
Output:Code:#include <stdio.h> #include <stddef.h> struct st{ char c; int i; short s; }; int main(){ printf("%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 ; }
Code:[Session started at 2008-04-08 00:02:17 -0500.] 12 0 4 8
Mainframe assembler programmer by trade. C coder when I can.
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."
try changing your struct to:
Code:struct st { int i; short s; char c; };
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
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.