I have a union having two struct variables. the struct contains a string (char array).
Here's my code:
#include <stdio.h>
#include <string.h>
int main(void) {
struct name{
char name_v[50];
};
union myunion{
struct name a;
struct name b;
}x;
strcpy(x.a.name_v, "HELLO PEEPS");
printf("%s\t%s", x.a.name_v, x.b.name_v);
return 0;
}
Since a union allocates enough memory to hold the highest value at a given time, I thought that the name_v of only struct name a will hold the value "HELLO PEEPS" and that of struct name b will hold '\0'.
However, the output of the above code is
HELLO PEEPS HELLO PEEPS
But I expected it to show something else (null?) in place of the second HELLO PEEPS.
So it seems that both the members of the union are being assigned the same value at the same time. (???)
• Why is this happening?
• Why am I not getting the expected output?
• What am I doing wrong that's not getting me to it?
I expect one of the union members to bear a null value when the other holds some valid value and want to be able to check that. Please help me to achieve this.