0

I need an explanation of the below code example regarding why its size is calculated as 32. As per my calculation and output that I get it comes as 28 , shown as follows :

size of price : 8 + size of title: 8 + size of author : 8 + size of number_pages : 4 Hence total : 8+8+8+4 = 28

Below is the code:

#include <stdio.h>  
struct store  
{  
    double price;  
    union  
    {  
        struct{  
        char *title;  
        char *author;  
        int number_pages;  
        } book;  
      
        struct {  
        int color;  
        int size;  
        char *design;  
        } shirt;  
    }item;  
};  
  int main()  
{  
    struct store s;  
    s.item.book.title = "C programming";   
    s.item.book.author = "John";  
    s.item.book.number_pages = 189;  
    printf("Size is %ld", sizeof(s));  
    printf("\nPrinting size of each items\n"); 
    print ("size of price = %ld\n", sizeof(s.price));
    print ("size of title = %ld\n", sizeof(s.item.book.title));
    print ("size of author = %ld\n", sizeof(s.item.book.author));
    print ("size of number_pages = %ld\n", sizeof(s.item.book.number_pages));

    return 0;  
}  

Am I making any mistake ? Any explanation will be great!

Thanks

  • 1
    Also note that the `sizeof` operator returns a value of type `size_t`. To print a `size_t` value, you need to use the `%zu` format. Mismatching format-specifier and argument type leads to *undefined behavior*. – Some programmer dude Oct 26 '22 at 07:05
  • 1
    Examine addresses of struct members to find out where the padding is. My _guess_ is, compiler wants even 8 byte alignment for the first `double`, so it adds 4 bytes of padding at the end, so in array this is alignment achieved. Possibly this is for performance reasons. – hyde Oct 26 '22 at 07:06
  • 1
    Your 28 doesn't account for *Padding* that the compiler is free to place anywhere within a struct (except before the first member) to maintain alignment. If the compiler is keeping a 16-byte alignment, then 32 would be the size of your struct with 4-bytes of padding sprinkled in. – David C. Rankin Oct 26 '22 at 07:07

0 Answers0