On VC++, why does the compiler only pad struct when non-char datatypes are used?
I.e.
struct TEST
{
char a[7];
};
struct TEST2
{
__int32 a;
char b[7];
};
sizeof(TEST); // Returns 7
sizeof(TEST2); // Returns 12
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It comes down to the fact that
sizeof(char) == 1— always.Arrays are required to be contiguous, so in an array of char (if it’s large enough), you end up with elements at every possible alignment. Since the compiler/hardware has to make that work, there can’t be a need to insert padding to deal with
charin something like astructeither.Now, that’s not to say that a compiler couldn’t insert padding. For example, it might be able to improve performance by doing so, even with an array of char. For example, given your
structdefinition, it would be perfectly acceptable for the compiler to pad your array of 7 char’s with one more to make the sizeof the struct 8 — a nice, neat power of 2.On some hardware, you’d be likely to see that. As it happens, the Intel hardware supported by VC++ doesn’t really benefit much from things like that, so you’re unlikely to see it there.