3,419 views
1 votes
1 votes

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;
}

 

A. 3, 2, 515
B. 515, 2, 3
C. 3, 2, 5
D. 515, 515, 4

Please Explain how to do such Questions On Union... 

1 Answer

Best answer
3 votes
3 votes

Basic Knowledge of Union is

1. Size of the Union = Size of Largest Member of it

2. only one member of a union is active at a time

3. all members shares the same memory address.


Your defined union have two members...

1) int =====================> size =4 B

2) character array of length 2  ===> size =2 B

Therefore size of Union is 4B

You updated the Char member of Union at last ===> Character array is having the original value.

what about " int " ? (assume your system is following little endian)

it access the total 4B ===> ch[1] ch[0] ====> 00000010 00000011 ===> 512+3 = 515 


if you have the doubt that why not accessing in the form of ch[0] ch[1] ====> 00000011 00000010 ===> 512+256+2 = 770

read about endian of the system https://www.geeksforgeeks.org/little-and-big-endian-mystery/

selected by

Related questions

3 votes
3 votes
1 answer
1
arpit.bagri asked Jul 26, 2023
640 views
What is the output of the code given below? #include <stdio.h #include <string.h union sample { int i; float f; char c; double d; char str[20]; }; int main() { // union s...
1 votes
1 votes
3 answers
2
shiva0 asked Apr 3, 2019
447 views
What is the output of the program? int main() { union a { int i; char ch ; }; union a u; u.ch[0] = 3; u.ch = 2; printf("%d, %d, %d", u.ch[0], u.ch , u.i); return 0; }
4 votes
4 votes
1 answer
4
ritwik_07 asked Jun 10, 2023
423 views
#include<stdio.h #include<string.h #define MAX(x, y) ((x) (y) ? (x) : (y)) int main() { int i = 10, j = 5, k = 0; k = MAX(i++, ++j); printf("%d %d %d", i, j, k); return ...