C Programming - Declarations and Initializations - Discussion
Discussion Forum : Declarations and Initializations - Find Output of Program (Q.No. 10)
10.
What is 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:
printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i); It prints the value of u.ch[0] = 3, u.ch[1] = 2 and it prints the value of u.i means the value of entire union size.
So the output is 3, 2, 515.
Discussion:
77 comments Page 4 of 8.
Deepak said:
1 decade ago
@Sahana
Its like multiplying contents inside memory location with index....like 512*1(see fig)...all other are zero......2*1 & 1*1
Its like multiplying contents inside memory location with index....like 512*1(see fig)...all other are zero......2*1 & 1*1
Ravali said:
1 decade ago
I am not able to understand. And @Nandini you have a good explanation but I have understood it partially can you explain t more deeply?
Sushma said:
1 decade ago
First of all why should we consider 8 bits to calculate size of union. Why not 16 bits or something else then the answer will change ?
Nutan said:
1 decade ago
u.ch[0] = 3;
u.ch[1] = 2;
The Above two statements is fine but when u try to access i value, how it becomes 515 sum of index.
u.ch[1] = 2;
The Above two statements is fine but when u try to access i value, how it becomes 515 sum of index.
Sahana said:
1 decade ago
Upto 512 calculation I can understand. But what about adding 2+1 with 512. So that we get the ans as 515. Please explain this.
Rajat said:
9 years ago
When we are changing char array to short array it's not doing the same thing. In my compiler size of int is 4 and short is 2.
Kavya said:
1 decade ago
How we got the answer has 515? Try to expalin in detail how to find the union size using same fig used in explaining answer.
Mahesh said:
6 years ago
How that I and other two char arrays are related ?
We are asked to find I and how we are relating it with other variables.
We are asked to find I and how we are relating it with other variables.
Anu said:
1 decade ago
Please could anyone explain me this one I cant get it how. I gives this value?and how to calculate the size of union?
Moon said:
1 decade ago
Please give an example and give a description? Why we use struct and union ? where can we use it (with an example) ?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers