What is the size of the structure in this code below, assuming we have a structure pad and int size is 4 and double size is 8 bytes

Can someone please tell me how the size of the structure shown below is 24, 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 assumption is that the size of the structure will be 20 if we consider the registration, but when I run this code, the size will print as 24.

+5
source share
2 answers

The size will be 24 . This is due to the fact that the last element is filled with the number of required bytes, so the total size of the structure must be a multiple of the largest alignment of any member of the structure.

Thus, the addition will look 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 details.

+6
source

Maybe the packed attribute will answer the question.

 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 } __attribute__((packed)) abc_t ; 
-1
source

Source: https://habr.com/ru/post/1257579/


All Articles