-
sizeof struct
I'm running the following prog :
Code:
#include <iostream>
using namespace std;
struct customer {
short number; // 1:
int postcode; // 2:
};
int main() {
cout<<sizeof(customer)<<endl;
}
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 it as it is above the outout is 8.Why is that?
Thank you in advance.
-
Because the compiler belives that aligning structs to 4- or 8-byte boundaries will make your program faster.
-
"Because the compiler belives that aligning structs to 4- or 8-byte boundaries will make your program faster."
???
That doesn't explain why sizeof (customer) will return 2 if there is only 1 short int, or 6 if there are 3 short ints (and no ints), yet if there are 3 short ints plus 1 int, it returns 12.
Does it align structs that way only when they contain ints?
-