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;
}
3, 2, 515
515, 2, 3
3, 2, 5
None of these
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 8 of 8.

Harika said:   6 years ago
Can anyone explain the memory allocation?

Please.

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.

Manjiree said:   6 years ago
Please can you explain in detail how it will calculate the entire size of the union?
(1)

Mesi said:   6 years ago
What will be the result if we add one more value u.ch[2]=4?

Sumith said:   6 years ago
Why would the "i" get the entire size of union?
(2)

Shaziya Hasan said:   5 years ago
How can we use %d for a character array? Can anyone explain?
(1)

Jayakumar v said:   4 years ago
Good explanation. Thanks, everyone.


Post your comments here:

Your comments will be displayed after verification.