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;
}
3, 2, 515
515, 2, 3
3, 2, 5
515, 515, 4
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 1 of 4.

Vijay said:   3 years ago
Here the concept is union memory management. union memory size is largest data member.

Here
data members are : int i ; char a[2];
largest data member is int ie 4bytes.
note := 1byte=8bits => 1byte= 00000000.

4byte := 00000000 00000000 00000000 00000000.

for char u.a[0]=3; => uses first byte in memory
ie , 00000000 00000000 00000000 " 00000011 "
for char u.a[1]=1 ; => uses second byte(system allocates or selects like this).
ie , 00000000 00000000 "00000001" 00000011
whenever we are printing u.a[1] points to its 1 byte and gives 3
Similarly u.a[2] points to the second byte give 1.

when printing u.i, it is not initialized so it took the first 4 bytes ie entire memory

ie "00000000 00000000 00000001 00000011" => its value in binary is 515
2^8 + 2^1 + 2^0 =512+2+1 =515
So,u[i] prints 515.
(6)

Vineeta said:   3 years ago
Please explain me, why use 8 binary bits 00000011?

Anyone explain about it.

Supraja said:   6 years ago
Here can we take union u instead of union a u?

Venkatg said:   6 years ago
Thanks @Dash.

Noel said:   7 years ago
Agree @Raju Kumar.

If I make the data types in the union ( int i; & char ch[2];) match (both int or both char, etc.) then the number of bytes match and I get a predictable and expected value for u.i. That is, it matches the value of what is in the ch[0] memory location.
(1)

Sana Shekijh said:   7 years ago
How to get ui? Please explain.

Zdd said:   7 years ago
#include<stdio.h>

int main()
{
union a
{
short int i;
char ch[2];
};
union a u;
u.ch[0]='a';
u.ch[1]='b';

printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
return 0;
}

Its output is:97, 98, 25185.

if I change 'short int' to 'char',then the output is; 97, 98, 97.

Oswald said:   7 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.

Akshata said:   7 years ago
#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, %d\n", u.ch[0], u.ch[1], u.ch[2], u.i);
return 0;
}

Getting ans as 3, 2, 110, -143785469.

How that 110 came? Please help

Bittu said:   8 years ago
Union uses Shared memory.

So, char[] and int i occupy the same memory location.


Post your comments here:

Your comments will be displayed after verification.