Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 507
user2520451 Avatar asked Oct 01 '16 12:10

user2520451


People also ask

What is the size of a struct C structure?

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.

What is the size of a structure in C language?

A) C structure is always 128 bytes.

What will be the size of the following struct for a 64-bit machine?

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).


1 Answers

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.

like image 50
haccks Avatar answered Sep 22 '22 18:09

haccks