Reputation: 7
I have a code that gives different values on different online compilers, I am new to C programming, please let me know if different values are expected while we run the following code on different c online compilers:
#include <stdio.h>
struct hai
{
char c;
long l;
char *p;
};
union bye
{
char c;
long l;
char *p;
};
int main (int argc, char *argv[])
{
struct hai myhai;
union bye mybye;
myhai.c = 1;
myhai.l = 2L;
myhai.p = "This is myhai";
mybye.c = 1;
mybye.l = 2L;
mybye.p = "This is mybye";
printf("myhai: %d %ld %s\n", myhai.c, myhai.l, myhai.p);
printf("mybye: %d %ld %s\n", mybye.c, mybye.l, mybye.p);
return 0;
}
Upvotes: 0
Views: 88
Reputation: 109532
In a union the fields are overlayed. Exactly how is undefined:
Upvotes: 0
Reputation: 67476
Union is the place where members share the same memory location. Union has only storage enough for the largest member of it.
Writing any of members overwrites at least the part of the memory occupies by other members.
In your case the at write is important. It stores the address of the string literal into the union. When you read the c
member you read the first byte of this address.
Upvotes: 2