Take the 2-minute tour ×

On VC++, why does the compiler only pad struct when non-char datatypes are used?


struct TEST
   char a[7];

struct TEST2
   __int32 a;
   char b[7];

sizeof(TEST); // Returns 7
sizeof(TEST2); // Returns 12
share|improve this question
This is completely compiler-specific. What compiler are you testing this in? –  templatetypedef Jun 15 '12 at 1:18
Oh, didn't realize! VC++. –  Qix Jun 15 '12 at 1:36

1 Answer 1

up vote 2 down vote accepted

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 char in something like a struct either.

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 struct definition, 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.

share|improve this answer
That makes sense. The same works without a char array (i.e. char c1, c2, ...). –  Qix Jun 15 '12 at 1:38
@Di-0xide: Not really -- two separately defined chars are not required to be contiguous. In an array they must be contiguous though (e.g., if the first char in an array is at xxxx0, then the next one must be at xxxx1). –  Jerry Coffin Jun 15 '12 at 1:39
Oh interesting - no I was referring to the padding the compiler performs. I received the same test results, at least in this scenario. –  Qix Jun 15 '12 at 1:40
@Di-0xide: It's not surprising to see the same (especially on Intel hardware), but in this case it could insert padding between them if it wanted, whereas in an array it's not allowed to. –  Jerry Coffin Jun 15 '12 at 1:42

Your Answer


