Hello friends ,
I was studing C++ late in night and I faced a little weird situation . I saw a code as follows:
class check
{
int i;
float j;
char k;
};
int main()
{
cout<<sizeof(check)<<endl;
check c;
cout<<sizeof(c)<<endl;
return 0;
}
As I was expecting the output 9,9 , but it didn’t give the same on my linux machine.
And then I came to know that byte packing is done here .
Linux being a 32-bit OS , so the object would be aligned on a 4-byte boundary.
Hence I got the output 12,12.
Isn’t it memory consuming ?
Well , we can overcome from this situation by using pragma.
We can force the alignment on a 1-byte boundary. To do this , we have to use
#pragma pack(1) just before the class declaration.But friends , one more thing is still left, you can’t use #pragma pack with any random number. The number in the paranthesis must be a small power of two. Otherwise you may get the warning stating the same.
So don’t wait , open your text editor and try this . ♥