user2520451 user2520451 - 2 months ago 7
C Question

What is the size of the structure in this code below assuming that we have structure padding and size of int is 4 and size of double is 8 bytes

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.

Answer

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.