-2

So I am currently a student and am having a programming couse.

Today we had about the use of sizeof in different classes(if it had 1 int or 2 int´s and so on)

One part of the example I found weird was this:

class TwoIntAndACharClass
{
public:
    int x_;
    int y_;
    char z_;
};

and the part to test it

TwoIntAndACharClass o3b;
cout << "Sizeof TwoIntAndACharClass          = " <<  sizeof(o3b) << "\n";

So in the program i could see a class with 1 char took 1 byte. So when I saw this I thought I would see 9 bytes and not 12

So first I thought that it was weird but after some time I came to the conclusion that it might save some kind of blocks of 4 bytes.

To be 100% sure that this was true I then tried adding a new variable into the class(a double variable of 8 bytes) and the total size increased from 12 bytes to now 24 bytes. That ment that the char now had to be 8 bytes long so my last theory failed.

My last theory was that it would take the biggest already declared variable and use the size of that for the char variable _z , as this worked with both long long int(8 bytes) and a double(also 8 bytes)

So my question is, is my last theory true - or is it something different making the char take more memory then needed? (my teacher did say that each compiler could handle this differently but I have tried it on microsoft visual studio and a friend tried it on another compiler with the same results, but is that really true, is it the way the compiler handle this?)

Sorry for my poor english.

Sumsar1812
  • 616
  • 1
  • 9
  • 32
  • Two words: Rounding error. Well, not exactly "error", but struct sizes are rounded up in various ways (and fields within the struct re-alighned) to suit the compiler, OS, and CPU. You can declare a struct "packed" to prevent this, though with some danger of the dreaded "undefined behavior". – Hot Licks Aug 26 '13 at 16:10
  • 1
    Why would you ask the question "why does sizeof show 4 bytes for a char", *when you haven't tried using `sizeof` on a `char`? Didn't it occur to you that that might be a useful experiment? ;) – jalf Aug 26 '13 at 16:35
  • Try adding another char to the end of you structure. How many times can you do this before the size of the class changes? – Martin York Aug 27 '13 at 03:53

1 Answers1

7

sizeof gives you the size of the struct, not the sum of the sizes of its members. Due to alignment requirements (ints generally like to be aligned on natural boundaries; 4 bytes on most platforms), the compiler will pad the struct to 12 bytes, so that when you have multiple instances of the struct adjacent to each other (e.g. in an array), they stay correctly aligned.

Most compilers have some custom extension to control padding, e.g. #pragma pack in Microsoft's compiler.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157