Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferenceing on casting the void pointer to float*/int*

Tags:

c

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.

like image 473
Amit Sharma Avatar asked Jan 21 '26 00:01

Amit Sharma


2 Answers

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.

like image 87
glglgl Avatar answered Jan 22 '26 16:01

glglgl


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.

like image 27
Christian Ternus Avatar answered Jan 22 '26 15:01

Christian Ternus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!