C Programming - Memory Allocation - Discussion

Discussion Forum : Memory Allocation - Find Output of Program (Q.No. 4)
4.
What will be the output of the program?
#include<stdio.h>
#include<stdlib.h>

int main()
{
    union test
    {
        int i;
        float f;
        char c;
    };
    union test *t;
    t = (union test *)malloc(sizeof(union test));
    t->f = 10.10f;
    printf("%f", t->f);
    return 0;
}
10
Garbage value
10.100000
Error
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
22 comments Page 1 of 3.

Raju Naidu said:   1 decade ago
@priya

t=(union test*)malloc(sizeof(union test));
Here malloc return different type that's y we've to do type conversion to original type..i.e union test*

Ex int i =5 valid here we r assigning the same type value so int type accepted
but int i=0.23 invalid,here we r assigning the float value it cannot possible so here typecasting is need.

int i=(int)0.23

Hms said:   1 decade ago
What does f in 10.10f imply?


I'd also like to know this, my guess would be that

t->f = 10.10f; equals t->f = 10.10 * f;

But I thought this in the exercise above it would output a garbage value since f was not initialized (ie contains garbage), according to the solution I am wrong.

Could anybody explain this to me?

Nirbhay singh said:   1 decade ago
'union test' is name of user define data type sothat sizeof() operator gives size of varriable used in that datatype and we know that malloc()takes integer argument which tells how many blocks will be created. (union test *) is simple type-casting which will say to compiler that created address is of 'union set' type.

Saif said:   5 years ago
Union allocated with the higher value in it i.e. float the during DMA pointer gets the address of float type then when initialization of value 10.10f is done it will print 10.100000 because float takes 6 digits after the decimal point.
(1)

The Guide said:   1 decade ago
malloc() returns pointer to void. That is, pointer to the first memory location of the allocated memory block. The pointer type is unknown at this point, hence typecasting is done later.

MDV AJAY said:   8 years ago
In this, t gets te dynamic address of 4 so it is assigned to f as t->f so 10.10f will becomes 10.100000 now we gotta know that f stands for 4 zeros.

Apple said:   1 decade ago
Hi Baru,

Since t->f=10.10f it gives the output as 10.100000 as it float takes 6 digits after the decimal point.

Ganesh said:   10 years ago
t = (union test *)malloc(sizeof(union test));

What value is there in "t"? Can you please explain in detail?

Balaji said:   9 years ago
@Ganesh.

t will be holding the address of the pointer pointing to union datatype.

Priya said:   1 decade ago
What is the meaning of :

t = (union test *)malloc(sizeof(union test));


Post your comments here:

Your comments will be displayed after verification.