A
int i = 10;
void *p = &i;
printf("%f\n", *(float*)p);
B
float i=10.00;
void *p = &i; // no change
printf("%d\n", *(int*)p);
Why does A print 0.0, not 10.0? If we change A to B, then its output is garbage.
int i = 10;
void *p = &i;
printf("%f\n", *(float*)p);
float i=10.00;
void *p = &i; // no change
printf("%d\n", *(int*)p);
Why does A print 0.0, not 10.0? If we change A to B, then its output is garbage.
To be more precise about what the others say, here is a test:
#include <stdlib.h>
int main()
{
int a = 10;
float b = 10;
char * p;
p = &a;
printf("int repr: %02x %02x %02x %02x\n", p[0], p[1], p[2], p[3]);
p = &b;
printf("float repr: %02x %02x %02x %02x\n", p[0], p[1], p[2], p[3]);
return 0;
}
The output is
int repr: 0a 00 00 00
float repr: 00 00 20 41
This shows:
a) It is a little endian machine, as the lowest byte of the int comes first in memory
b) the int has the representation with the bytes 0a 00 00 00
, so the value is 0000000a
, the hex representation of, well, 10.
c) the float is indeed 41200000
. According to IEEE 754, this means you have one sign bit, 8 bits of exponent and 23 bits of mantissa. The sign is 0 (+), the exponent is 0x82
, meaning +3, and the mantissa is 010000...
, which means 1.01 in binary or 1.25 in decimal.
Together, these data form the value 2*2*2*1.25 = 8*1.25 = 10.
Because you're not really doing a cast in the first case -- you're casting pointer types.
If you want 10.0, here's how you'd do it:
int i = 10;
printf("%f\n", (float)i);
Here's what you're doing now:
int i = 10; // Create int i and initialize to 10.
void *p = &i; // Get an untyped pointer and set it to the address of i
printf("%f\n", *(float*)p); // Treat the pointer p as a float pointer and dereference it, printing it as a float.
Since int
and float
have different representations, there's no reason to believe this would work.
Basically what you are doing is you are casting a void *
to a float *
/int *
, i.e, you are casting pointer types and then dereferencing them. Since the dereferencing operation behaves differently depending on the type, there is no reason to beilieve this should work. You can try this code and see the difference :
int i = 10;
void *p = &i;
printf("%d\n", *(int*)(p));