Thinking about casting a void pointer for float * / int *

A

int i = 10; void *p = &i; printf("%f\n", *(float*)p); 

IN

 float i=10.00; void *p = &i; // no change printf("%d\n", *(int*)p); 

Why is A print 0.0 and not 10.0? If we change A to B, then its output will be garbage.

+2
source share
3 answers

To be more precise about what others are saying, 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; } 

Output signal

 int repr: 0a 00 00 00 float repr: 00 00 20 41 

It shows:

a) This is a little finite machine, since the low byte of int comes first into memory b) int has a representation with bytes 0a 00 00 00 , so the value is 0000000a , a hexadecimal representation, well, 10. c) the float is really 41200000 . According to IEEE 754 , this means that you have one sign bit, 8 exponent bits, and 23 mantissa bits. The sign is 0 (+), the exponent is 0x82 , which means +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.

+5
source

Because you are not casting in the first case, you are producing pointer types.

If you want 10.0, here is how you do it:

 int i = 10; printf("%f\n", (float)i); 

Here is what you are 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 views, there is no reason to believe that this will work.

+4
source

Basically, you do void * float * / int * , i.e. you produce pointer types and then cast them. Since the dereferencing operation behaves differently depending on the type, there is no reason for it to be necessary. You can try this code and see the difference:

 int i = 10; void *p = &i; printf("%d\n", *(int*)(p)); 
0
source

Source: https://habr.com/ru/post/1238864/


All Articles