0

I am trying to learn memory allocation in c for union and having a problem trying to do so

#include <stdio.h>
union abc
{
    int a;
    char name[5];
};

int main()
{
    union abc hh;
    printf("Enter two values\n");
    scanf("%d%s",&hh.a,&hh.name);
    printf("Values are\n");
    printf("%d\n%s",hh.a,hh.name);

    return 0;
}

As seen in the above code i am trying to store two values in a union.But however the result i am getting after enter values as '23' and 'p' is

Enter two values                                                                                                                 
23                                                                                                                              
p                                                                                                                                
Values are                                                                                                                       
112                                                                                                                              
p   

Can someone help me regarding above code

Barmar
  • 741,623
  • 53
  • 500
  • 612
P.Bendre
  • 55
  • 1
  • 6
  • Do you understand the difference between a `struct` and `union`? If so, it should be obvious why this doesn't work. – Barmar Feb 10 '18 at 06:43
  • A union uses the same memory for both members. You can't store two values in it. – Barmar Feb 10 '18 at 06:45

1 Answers1

1

The members of a union share the same space in memory. This means that writing to one member overwrites the data in all other members and that reading from one member results in the same data as reading from all other members.

With this thing on mind you will see the initial value 23 is overwritten and we get the ascii value of p which is 112 when we print it our after storing p there. This explains the behavior you saw.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • I got ya' but still the total memory allocated is 5 bytes for the union and according to the input '23' will consume 4 bytes while 'p' will do the remaining 1 byte.So how will they overwrite each other.Thanks anyway – P.Bendre Feb 10 '18 at 07:03
  • @P.Bendre.: Because it's the same memory that is being written to. 5 bytes has nothing to do with it....here 4 bytes are used to write the int and then taht is overwrittem by `p` and `\0`. It might not be 5 bytes it is atleast 5 byts..it can be greater also – user2736738 Feb 10 '18 at 07:06