Convert double to void * in C

I am writing an interpreter, and I would like to be able to store any value returned by the function in the void pointer. I had no problems storing ints and various pointers as void pointers, but I get an error when trying to use double as a void pointer. I understand that doubles are stored differently than integers and pointers at the bit level, but I don’t understand why I cannot put any bits that I want in the pointer (assuming that it has enough allocated memory), and then bring them out later, casting them like a double.

Is it possible to use a double pointer to void using syntax that I don’t know about, or I don’t understand how void pointers work?

+6
source share
3 answers

On many systems, a double is 8 bytes wide, and a pointer is 4 bytes wide. Consequently, the former would not be included in the latter.

You seem to be abusing void* . Your decision will include allocating storage space of at least the same size as the largest type that you need to store in some similar variant structure, for example. a union .

+12
source

Of course you can drop it. Void pointers are what make polymorphism possible in C. You need to know in advance what you are passing to your function.

 void *p_v ; double *p_d ; p_d = malloc( sizeof( double ) ) ; p_v = ( void * ) p_d ; 
+2
source

There he is

 int main ( ) { double d = 1.00e+00 ; // 0x3ff0000000000000 double * pd = & d ; void * * p = ( void * * ) pd ; void * dp = * p ; printf ( "%f %p %p %p \n" , d , pd , p , dp ) ; return 0 ; } ; 

Exit

 1.000000 0x7fff89a7de80 0x7fff89a7de80 0x3ff0000000000000 

The second and third addresses may vary. Label

 void * dp = * ( void * * ) & d ; 

Greetings

0
source

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


All Articles