sizeof operator

B

bintom

class MyClass
{ int i;
char ch;
};

int main()
{ cout << sizeof(MyClass); }


Under Turbo C++, the above code gives sizeof 'MyClass' as 2 + 1 = 3
bytes.

But under Dev C++ and MS VC++, whereas it should give 4 + 1 = 5 bytes,
it is showing 8 bytes. Why?

Thanks in advance,

Binoy Thomas
 
D

Default User

bintom said:
class MyClass
{ int i;
char ch;
};

int main()
{ cout << sizeof(MyClass); }


Under Turbo C++, the above code gives sizeof 'MyClass' as 2 + 1 = 3
bytes.

But under Dev C++ and MS VC++, whereas it should give 4 + 1 = 5 bytes,
it is showing 8 bytes. Why?

What makes you think that it "should" have that value? The implementation is
allowed to pad between members or after the final member.



Brian
 
B

bintom

So that i is always correctly aligned. Consider an array of MyClass:
MyClass a[2];
if sizeof(MyClass) was 5 bytes then a[1].i would not be correctly aligned.


Hi Leigh,

I didn't get what you meant by 'correctly aligned'. Could u elaborate?

Binoy Thomas
 
I

Ian Collins

doesn't sizeof have the type of size_t?

size_t is defined as

"the unsigned integer type of the result of the sizeof operator"

But how was that relevant to the original question?
 
J

Juha Nieminen

bintom said:
But under Dev C++ and MS VC++, whereas it should give 4 + 1 = 5 bytes,
it is showing 8 bytes. Why?

The size of a struct is not the sum of the sizes of its members.
It's the minimum size that is required for the struct to be properly
instantiated (for example as an array of such structs) without causing
problems (or in some architectures, while still being as efficient as
possible).

For example, if you allocate an array of such structs, the amount of
space allocated for each element must be such that each element starts
from a properly aligned memory location. (Not doing so would cause bad
inefficiency in some architectures, such as Intel's, and an outright
crash in others, such as in UltraSparc architectures.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,143
Messages
2,570,822
Members
47,368
Latest member
michaelsmithh

Latest Threads

Top