0

I wrote the following code just to verify what was written in one of the books I use to study c. the memory allocated to the first variable i.e character variable does not make sense. the memory allocated is 4 bytes instead of 1.can someone help me where did i go wrong?

    struct book
    {
        char name;
        int price;
        int pages;
    };
    struct book b1={'a',23,45},b2={'d',56,34},b3={'e',38,79};
    printf("%p\t %p\t %p\n",&b1,&b2,&b3);
    printf("%p\t %p\t %p\n",&b1.name,&b1.price,&b1.pages);
0x7ffd4f9a0384     0x7ffd4f9a0390     0x7ffd4f9a039c
0x7ffd4f9a0384     0x7ffd4f9a0388     0x7ffd4f9a038c
adithya
  • 21
  • 5
  • Where are you getting the idea that four bytes are being allocated for `name`? Your output just shows the addresses of your structs. – Pierce Griffiths Apr 27 '19 at 19:07
  • i edited it, can you please check it now. – adithya Apr 27 '19 at 19:10
  • Padding may be inserted automatically to ensure later members are naturally aligned. Compare with `struct b{char a; char b;};` and `offsetof(struct b, b}` – EOF Apr 27 '19 at 19:11

1 Answers1

0

It seems that you're confusing addresses with size. The printf statements should be be written like this:

printf("%zu\t %zu\t %zu\n", sizeof(b1), sizeof(b2), sizeof(b3));
printf("%zu\t %zu\t %zu\n", sizeof(b1.name), sizeof(b1.price), sizeof(b1.pages));

This gives you the following output:

12       12      12
1        4       4

As for why the structs are 12 bytes in size while only holding 9 bytes of data, that has to do with struct alignment.

Pierce Griffiths
  • 733
  • 3
  • 15