-
sizeof struct
I'm running the following prog :
Code:
#include <stdio.h>
struct customer {
short number; // 1:
int postcode; // 2:
};
int main() {
printf("%d\n",sizeof(customer));
}
If I run it with line 1 in comments the output is 4.OK for that.
If I run it with line 2 in comments the output is 2.OK for that too.
But if i run as it is above the outout is 8.Why is that?
Thank you in advance.
-
sizeof(struct customer);
or typedef and you could use just customer.
-
Basically i did it in C++ that's why I wrote :
printf("%d\n",sizeof(customer));
But even with printf("%d\n",sizeof(struct customer));
it prints 8.Why?
-
and what you expect to print? sizeof returns you the size of this struct, not how many elements you have on it. So 8 is perfect, look:
Code:
struct customer {
short number; // sizeof(short) == 4!
int postcode; // sizeof(int) == 4!
//4+4 = 8
};
-
The sizeof(short) is 2 not 4.
-
well, it's really machine dependent... but in your case if it's 2, and you're still receiving 8, strange.
-
when i run :
printf("%d",sizeof(short));
it prints 2 but when i run the program with the struct it prints 8.
-
Its to do with struct member alignment. Code can be compiled with different alignments either 1, 2, 4, 8, 16 bytes (MS VC++ 6), 8 is the default setting. I compiled the code different alignments:
1 byte - sizeof = 6
2 byte - sizeof = 6
4 byte - sizeof = 8
8 byte - sizeof = 8
16 byte - sizeof = 8
-
did you try to use another compiler and see what happens maybe you compiler add something to optimize the code?
-
The compiler had to add a couple bytes because of alignment restrictions. If you need 6 bytes exactly, try looking for some "packed" pragma's, or compiler-specific keywords used after "struct". Why is this a problem in your case? There might be an easier work-around.