C Programming - Structures, Unions, Enums - Discussion
Discussion Forum : Structures, Unions, Enums - Find Output of Program (Q.No. 1)
1.
What will be the output of the program ?
#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0]=3;
u.ch[1]=2;
printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
return 0;
}
Answer: Option
Explanation:
The system will allocate 2 bytes for the union.
The statements u.ch[0]=3; u.ch[1]=2; store data in memory as given below.
Discussion:
40 comments Page 2 of 4.
Karthik said:
1 decade ago
u.ch[0]=3;
u.ch[1]=2;
Now u.i is calculated as
(2)(3) in binary form which is equal to 515.
(2) --> 00000010; (3) --> 00000011
(2)(3) --> 0000001000000011 --> 515.
u.ch[1]=2;
Now u.i is calculated as
(2)(3) in binary form which is equal to 515.
(2) --> 00000010; (3) --> 00000011
(2)(3) --> 0000001000000011 --> 515.
Oswald said:
8 years ago
But union takes the memory of maximum size variable. So, in this case, int i has 4 bytes which is greater than value of ch[2] (2 elements * sizeof(char)) = 2 bytes.
Ashwini said:
1 decade ago
@Ashish
When I compile it in Turbo c++ IDE
It has given output as: 3 2 0 50
not u.ch[2] as 20
and I think 50 as garbage value, So how u.ch[2] as 0 ?
When I compile it in Turbo c++ IDE
It has given output as: 3 2 0 50
not u.ch[2] as 20
and I think 50 as garbage value, So how u.ch[2] as 0 ?
Sai said:
1 decade ago
@karthik i cant get you
Please explain in detail
(2)(3) --> 0000001000000011 --> 515.
how it came..
I am a begineer, please help me some one.
Please explain in detail
(2)(3) --> 0000001000000011 --> 515.
how it came..
I am a begineer, please help me some one.
Ganesanttl said:
1 decade ago
Is there any restriction to use char in union should contain one int value ? suppose replaced int i to any other (char i, float i. ) what happen ?
Sree said:
1 decade ago
@Sai
The binary value of 2 is 00000010 and dat of 3 is 00000011...
Now (2)(3)---> 0000001000000011 = 2^9 + 2^1 + 2^0 = 515
The binary value of 2 is 00000010 and dat of 3 is 00000011...
Now (2)(3)---> 0000001000000011 = 2^9 + 2^1 + 2^0 = 515
(1)
Tharindu said:
1 decade ago
I want to know how to write this code.
1st reduce the value of A by 1 then find sum A and B then incriment B by 1?
1st reduce the value of A by 1 then find sum A and B then incriment B by 1?
Ramkumar said:
1 decade ago
u.ch[0]='a';
u.ch[1]='b';
Can anyone explain output for this definition instead of u.ch[0]=3;
u.ch[1]=2;?
u.ch[1]='b';
Can anyone explain output for this definition instead of u.ch[0]=3;
u.ch[1]=2;?
Kumar said:
1 decade ago
u.ch[0]=3;
u.ch[1]=2; for calculating (u.i) why we are taking 2 as first and 3 as second value?
u.ch[1]=2; for calculating (u.i) why we are taking 2 as first and 3 as second value?
Arjun said:
1 decade ago
I understood how 515 is printed. I don't understand Why does doing u, i print that value?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers