Can anyone please tell me how come the size of the structure shown below is 24 and not 20.
typedef struct
{
double d; // this would be 8 bytes
char c; // This should be 4 bytes considering 3 bytes padding
int a; // This would be 4 bytes
float b; // This would be 4 bytes
} abc_t;
main()
{
abc_t temp;
printf("The size of struct is %d\n",sizeof(temp));
}
My asumption is that the size of structure would be 20 when we consider padding but when i run this code the size is printing as 24.
In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes. Structure padding is used to save number of CPU cycles. Let's see what compiler is giving using the sizeof() operator.
A) C structure is always 128 bytes.
Personally, I think no matter the program is 32-bit or 64-bit , the size of structure should always be 16 bytes (since char is 1 byte long, and the alignment of double is 8 bytes).
Size would be 24
. It is because the last member is padded with the number of bytes required so that the total size of the structure should be a multiple of the largest alignment of any structure member.
So padding would be like
typedef struct
{
double d; // This would be 8 bytes
char c; // This should be 4 bytes considering 3 bytes padding
int a; // This would be 4 bytes
float b; // Last member of structure. Largest alignment is 8.
// This would be 8 bytes to make the size multiple of 8
} abc_t;
Read the wiki article for more detail.
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