0

need explonation in detail

why we use void instead of int and *(float *)p in printf #include<stdio.h> int main() { int i = 10; void *p = &i; printf("%f\n", *(float *)p); return 0; }

5th Mar 2020, 3:44 PM
Reiner
Reiner - avatar
2 Antworten
+ 1
in this code example, what the cast is applied to is the supposed type not the real one since p is an untyped pointer. Usually if you take an int and cast to float, you get the transformation of the integer stored complement to 2 in the memory area into the equivalent number stored as a floating point number in the IEEE754 standard. In both variables you will find the value 10. In the example instead, you are asked to evaluate the int value 10 in the IEEE754 standard so that 10 is in the mantissa which is the part after the comma and moreover it is a very small number. I tried the code and the 10 stored as int equates to 1.401298e-44 if evaluated as float. The %f give 0.00000, if you use %e you can read it in scientific notation. Infact, if you try float f=1.401398E-44; void* p=&f; printf("%d",*(int*)p); the result is 10 😋 therefore, for the same binary representation, a float is very different from an int 😁
7th Mar 2020, 1:32 AM
Ciro Pellegrino
Ciro Pellegrino - avatar
0
A void pointer variable can point to the address of data irrespective of the type of data stored in that address. At the time of printing it you can typecast it to the type you are pointing to or any other type.
5th Mar 2020, 3:56 PM
Avinesh
Avinesh - avatar