Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting double to void* in C

I'm writing an interpreter and I'd like to be able to store whatever value a function returns into a void pointer. I've had no problem storing ints and various pointers as void pointers but I get an error when trying to cast a 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 can't place whatever bits I want into the pointer (assuming it has enough memory allocated) and then take them out later, casting them as a double.

Is it possible to cast a double to a void pointer using syntax I'm not aware of or am I misunderstanding how void pointers work?

like image 535
Jack Avatar asked Jul 04 '11 19:07

Jack


People also ask

What is a void * pointer in C?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers.

How do I cast a void pointer to a double?

If n won't be changed in main after calling pthread_create , you can pass a pointer to the n variable in main itself (i.e. (void*)&n , then use *(double*)num inside calc_fib ).


2 Answers

On many systems a double is 8 bytes wide and a pointer is 4 bytes wide. The former, therefore, would not fit into the latter.

You would appear to be abusing void*. Your solution is going to involve allocating storage space at least as big as the largest type you need to store in some variant-like structure, e.g. a union.

like image 88
David Heffernan Avatar answered Oct 02 '22 19:10

David Heffernan


Of course it's possible to cast it. Void pointers is what makes polymorphism possible in C. You need to know ahead of time what you're passing to your function.

void *p_v ;
double *p_d ;
p_d = malloc( sizeof( double ) ) ;
p_v = ( void * ) p_d ;
like image 43
James Avatar answered Oct 02 '22 18:10

James