Neelanjan Akuli Neelanjan Akuli - 1 month ago 23
C Question

Pointer type casting to different data type

what does

(float*)
specially do in case of g. If I write
g = *&i;
then the ouptut is normal i.e. g=f, but if
g = *(float*)&i;
then why is g=0.0000???

#include <stdio.h>

int main()
{

int i = 37;
int *p;
p = &i;
float f = i;
printf("%d\n", i);
printf("%d\n", p);
printf("%d\n", *p);
float g = *(float*) &i;
printf("i = %d f = %f g = %f", i, f, g);
}

Answer

g = *&i is the same as g = i and is assignment of an int into a float. The compiler performs a conversion through the = operator:

  1. Load integer, 2. convert as floating point format, 3. store in float. Works great beside the rounding problems.

The other construction is reinterpreting an integer pointer to a float pointer. Since data formats are different for floats (float is generally using some bits for mantissa and some bits for exponent) and for ints (ints are just serialized to memory 8-bit by 8-bit), the compiler just copies the data from source to destination without any extra conversion and you don't get what you want.