I know that a char and an int are calculated as being 8 bytes on 32 bit architectures due to alignment, but I recently came across a situation where a structure with 3 shorts was reported as being 6 bytes by the sizeof operator. Code is as follows:
#include <iostream>
using namespace std ;
struct IntAndChar
{
int a ;
unsigned char b ;
};
struct ThreeShorts
{
unsigned short a ;
unsigned short b ;
unsigned short c ;
};
int main()
{
cout<<sizeof(IntAndChar)<<endl; // outputs '8'
cout<<sizeof(ThreeShorts)<<endl; // outputs '6', I expected this to be '8'
return 0 ;
}
Compiler : g++ (Debian 4.3.2-1.1) 4.3.2. This really puzzles me, why isn't alignment enforced for the structure containing 3 shorts?
Size of the struct should be sum of all the data member, which is: Size of int n1+ size of int* n2 +size of char c1+ size of char* c2. Now considering the 64-bit system, Size of int is 4 Bytes. Size of character is 1 Byte. Size of any pointer type is 8 Bytes.
The size of the entire structure is 8 bytes. On knowing the structured padding, it is easier to redesign or rewrite the structure.
That's because int
is 4 bytes, and has to be aligned to a 4-bytes boundary. This means that ANY struct
containing an int
also has to be aligned to at least 4-bytes.
On the other hand, short
is 2 bytes, and needs alignment only to a 2-bytes boundary. If a struct
containing short
s does not contain anything that needs a larger alignment, the struct
will also be aligned to 2-bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With