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 1 of 8.

Nguyen Tien Thinh said:   1 decade ago
A structure is a collection of items of different types; and each data item will have its own memory location. Where as only one item within the union can be used at any time, because the memory allocated for each item inside the union is in a shared memory location i.e., only one memory location will be shared by the data items of union.

Size of union will be the size of the biggest variable.

Why do we need Union in the first place?

Sometimes we may not need the data of all the (related) data items of a complex data structure and be storing/accessing only one data item at a time. Union helps in such scenarios.

e.g.,
typedef union
{
int Wind_Chill;
char Heat_Index;
} Condition;

typedef struct
{
float temp;
Condition feels_like;
} Temperature;

Wind Chill is only calculated when it is cold and heat index is used only when it is hot. There is no need for both of them at the same time. So when we specify the temp, feels_like will have only one value - either wind chill or heat index, but not both.

The following simple program illustrate the above explanation:
% cat structunion.c
#include <stdio.h>
#include <stdlib.h>

typedef union
{
int Wind_Chill;
char Heat_Index;
} Condition;

typedef struct
{
float temp;
Condition feels_like;
} Temperature;

void main()
{
Temperature *tmp;

tmp = (Temperature *)malloc(sizeof(Temperature));

printf("\nAddress of Temperature = %u", tmp);
printf("\nAddress of temp = %u, feels_like = %u",
&(*tmp).temp, &(*tmp).feels_like);
printf("\nWind_Chill = %u, Heat_Index= %u\n",
&((*tmp).feels_like).Wind_Chill, &((*tmp).feels_like).Heat_Index);
}

% cc -o structunion structunion.c

% ./structunion
Address of Temperature = 165496
Address of temp = 165496, feels_like = 165500
Wind_Chill = 165500, Heat_Index= 165500

Anonymous said:   10 years ago
"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." is the explanation by the indiabix.

The last words 'value of entire union size' doesn't means size of the union rather the value represented when entire union is considered as integer of 2 bytes.

Bit confusing. C stores the information in 0s and 1s,

When one say, "Hey! will you please store an int for me" for a machine with int size 2 byte will store the binary equivalent of that number in 2 bytes for example to store decimal 2 it will store 00000000 in 1st byte and 00000010 in second byte, at time of retrieval C will read 2 consecutive bytes change it into decimal and will output it for you.

When one say, "Hey! will you please store a character for me. "Machine will reserve 1 byte of memory and store ascii value of the character in that one byte. For example if character is 'a' ASCII value 65 (Binary:- 01000001) is stored in that byte. At time of retrieval the ASCII code will be changed to corresponding character.

In the case we are discussing the char1 and char0 are stored at memory location say 2000 and 2001, at time of reading (when printf ("%d", u.i) ) , an integer is read at location 2000 (yes, the beauty of union!) and C reads the 2 bytes 2000 and 2001 that are 00000011 and 00000010 c combines it to make 0000000100000011 which is binary for 515.
(1)

Deepak said:   1 decade ago
@anonymous..
In that program first we assign u.ch[0]=3 which is array which index 0. so it takes memory in first byte and which is 00000011.

And then u.i=1;
Which REPLACE previous assigned memory of ch[0] and now it become 00000001

And then u.j=2;
Again REPLACE previous assigned memory of i and now it become 00000010

And now u.ch[1]=5 it takes memory in second byte and it is 00000101.

NOW IN MEMORY (00000101)(00000010)
second first byte
AND NOW printf("%d,%d,%d,%d",u.ch[0],u.ch[1],u.i,u.j); statement run.
IN THIS STATEMENT u.ch[0] is print the value which is in first byte. so we convert first byte binary digit in decimal numbers and get 2. so "u.ch[0]=2".

AFTER THAT u.ch[1] RUN AND IT print the value which is in SECOND byte. so we convert SECOND byte binary digit in decimal numbers and get 2. so "u.ch[0]=5".

And u.i run which means the whole memory takes by union so we convert 0000010100000010 into decimal numbers.which you know how convert binary to decimal.

And u.j also means the same

Deepak said:   1 decade ago
@anonymous..
In that program first we assign u.ch[0]=3 which is array which index 0. so it takes memory in first byte and which is 00000011.

And then u.i=1;
Which REPLACE previous assigned memory of ch[0] and now it become 00000001

And then u.j=2;
Again REPLACE previous assigned memory of i and now it become 00000010

And now u.ch[1]=5 it takes memory in second byte and it is 00000101.

NOW IN MEMORY (00000101)(00000010)
second first byte
AND NOW printf("%d,%d,%d,%d",u.ch[0],u.ch[1],u.i,u.j); statement run.
IN THIS STATEMENT u.ch[0] is print the value which is in first byte. so we convert first byte binary digit in decimal numbers and get 2. so "u.ch[0]=2".

AFTER THAT u.ch[1] RUN AND IT print the value which is in SECOND byte. so we convert SECOND byte binary digit in decimal numbers and get 2. so "u.ch[0]=5".

And u.i run which means the whole memory takes by union so we convert 0000010100000010 into decimal numbers.which you know how convert binary to decimal.

And u.j also means the same

Mostafa Hamoda said:   7 years ago
Guys let's take it easy.

The function of the union is to calculate the size of each of the variable contained in it and find the biggest size of them and then create a place on memory of that size, so in this example a 4 bytes space of memory is reserved for our union, in our usage we created an object (u) which have access to our four bytes, our first assignment was to put a value of 3(u.ch[0]) in the first byte because our array is of type character so our object will deal with only the first byte and initialize the rest of them with (zeros), and the second byte with 2 (u.ch[1]) now in our memory we should have a shape like this:

00000000 00000000 00000010 00000011
(ch[1]) (ch[0])
[ ONE INTEGER].

Now, when we used our object to access the memory and deal with info side as if it were an integer.

So the value would be (1*2^0+1*2^2+1*2^9) = 515.
(3)

Naveen said:   1 decade ago
@Suman sagar.

Consider it has a memory cell.

These are 2 memory cell(1byte =8 bits) ,size of the union is 2memory cells u.ch[0] occupies 1st memory cell ie 1-128, u.ch[1] occupies 2nd memory cell ie 256-65536. value assigned to u.ch[0] is 3 indicate the in 1st memory cell, u.ch[1] is assigned 2 indicate that is 2nd memory cell look for u.ch[1] it is like starting 1-128 but 1-65536 is one memory cell as a whole for the union.

u.ch[2] view   128 64 32   ....  2   1    |  128  ..  4   2   1   

u[i] view     65536  .. 1024   512    256 |  128   64..  2    1  

                               1     0                   1    1   


So according to u.ch[1] its value is 2.
But according to u[i] its value is 512 + 2+ 1.
Int occupies two memory cells whereas char occupies 1 memory cell.

Swetha92 said:   1 decade ago
I tried out this

#include<stdio.h>
int main()
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0] = 3;
u.ch[1] = 2;
u.ch[2] = 7;
printf("%d, %d, %d, %d\n", u.ch[0], u.ch[1], u.ch[2], u.i);
return 0;
}

I got the ans as 3,2,7,459267 and I also verified manually

But can u explain me why when char[2] declaration changed to char[3] gives result as 3,2,7,134676995

I mean I get the above result for the following program

#include<stdio.h>
int main()
{
union a
{
int i;
char ch[3];
};
union a u;
u.ch[0] = 3;
u.ch[1] = 2;
u.ch[2] = 7;
printf("%d, %d, %d, %d\n", u.ch[0], u.ch[1], u.ch[2], u.i);
return 0;
}

What does char[2] and char[3] declarations actually do to the program?
Pls explain me.

Naziya said:   9 years ago
Explanation to the given question is as follows. As we know union size is the biggest size of its element, hence integer is considered to be the biggest.

Here integer is considered to be 4 bytes which are equal to 32 bits (GCC compiler). The memory allocation is as follows. 0000000000000000000000010000000011.

Hence from the above figure u.ch[0] = 3 & u.ch[1]=2.

As the character is of 1 byte.

So in that 4 bytes itself u.ch[0] and u.ch[1] can be occupied, as we are considering the biggest element to b integer, in other words, memory is shared.

So when we see u.i value is equivalent to 512 (the value at 10th bit) +2 (the value at 1st bit) +1 (the value at 0th bit). Therefore 512 + 2 + 1 = 515.

Soma said:   1 decade ago
It is a character array of size 2 byte because char in c is of 1 byte.

The value to be filled in the array field at index 0 is three.

And three is represented as 11 in binary and you have represent 11 in 8-bits, therefore the last two bit is set to 1 and rest zero at array index zero. And at array index one fill 2 which is represented by 10 and the rest field set to 0.

Now calculate the positional weight of the whole union. You will get the ans.

Srujan reddy said:   1 decade ago
%d is a format specifier for integer. So when u use %d in printf() statement for a character it will print the ascii value of that character? Explain in detail how could the solution gain those output value.

union has two variables indeed. the one is an integer and a character sequence of 2.

So memory is allocated either for int variable or for character sequence. but could you access the all the variables of the union at a time?


Post your comments here:

Your comments will be displayed after verification.