-1

I want to check the size of the variable arr. My question is why i am getting the size of arr 56 instead of 50. Because, as far as i know, union allocates the memory of the highest data type declares in union. Here in the union student char name[50] has the highest size.

#include <stdio.h>
#include <string.h>
union student
{
    int roll;
    double marks;
    char name[50];
};
int main()
{
    union student arr;
    printf("%d",sizeof(arr));

return 0;
}
timrau
  • 22,578
  • 4
  • 51
  • 64
  • 3
    The C standard says nothing about what the size of the union must be, so 56 isn't "wrong." The compiler probably chose to make the size a multiple of 8 for alignment or ABI reasons. – Gene Oct 03 '21 at 19:32
  • Can you please briefly explain it more. As I am not clear enough though. – Arafat_19AK Oct 03 '21 at 19:34
  • 1
    Does this answer your question? [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) –  Oct 03 '21 at 19:36
  • 1
    @StaceyGirl it is wrong. Structs and unions are different – 0___________ Oct 03 '21 at 19:39
  • Thanks. Now i understand. @StaceyGirl – Arafat_19AK Oct 03 '21 at 19:49
  • @0___________ True. But the answer is basically the same. ;) – klutt Oct 03 '21 at 20:09

1 Answers1

1

It is due to the alignment to the double.:) sizeof( double ) is equal to 8. 56 is divisible by 8. So if you will have for example an array of objects of the unit type then stored doubles will be aligned properly.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • alignment only can change the start address of the union, not its size. I rather suspect padding at the end of the union – 0___________ Oct 03 '21 at 19:43
  • 1
    @0___________ To make the start address aligned you need to "align" the size of the unit. Otherwise how are you going to use the pointer arithmetic? – Vlad from Moscow Oct 03 '21 at 19:47