Reputation: 133
Trying to understand the behaviour of union
#include <stdio.h>
struct abc{
unsigned long a;
unsigned long b;
// unsigned long c;
};
union temp
{
struct abc a;
unsigned long arr[2048];
};
int main()
{
union temp temp;
temp.a.a = 3;
temp.a.b = 'a';
// temp.a.c = 2;
printf("add : 0x%x 0x%x 0x%x \n", temp.a.a, temp.a.b, temp.arr[0]);
printf("add : 0x%x 0x%x \n",temp.a,temp.arr[0]);
return 0;
}
Output:
add : 0x3 0x61 0x3
add : 0x3 0x61
Question: why in second printf variable "temp.arr[0]" is printing 0x61 while it should print again 0x3?
Upvotes: 1
Views: 137
Reputation: 556
What does the program do at the second printf ?
printf("add : 0x%x 0x%x \n",temp.a,temp.arr[0]);
First the arguments are pushed on the stack. Apparently the first argument to be pushed is temp.arr[0], then temp.a is pushed. So your stack will contain the entire temp.a variable ie : 3,'a' followed by temp.arr[0]. Printf looks at the format string and as asked to print an integer pops the first 3, when asked to pop another int it pops the 'a'=0x61.
To get the right output simply give temp.a.a
as parameter.
Upvotes: 1
Reputation: 992
In the below line first two format specifiers were consumed by the temp.a.a and temp.a.b because you are passing the whole structure variable not an individual member.
printf("add : 0x%x 0x%x \n",temp.a,temp.arr[0]);
So there is no format specifier left for temp.arr[0] to print its value to console. You should provide a third format specifier or change the temp.a to temp.a.a
printf("add : 0x%x 0x%x 0x%x \n",temp.a,temp.arr[0]);
This will print the same output as the first print statement. i.e. add : 0x3 0x61 0x3
Upvotes: 0
Reputation: 6039
In your second printf
you have
temp.a
which is not what you want.
If you change it to temp.a.a
it will work as expected.
Upvotes: 1
Reputation: 575
You can define a union with many members, but only one member can contain a value at any given time.
In union you have to store in any data member and then access it using same data member. If you want to access from different data member then store it before accessing using that member. See the example below.
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
Ans would be
data.i : 10
data.f : 220.500000
data.str : C Programming
Upvotes: 0