Converting double to void* in C

…衆ロ難τιáo~ 提交于 2019-12-17 20:11:15

问题


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?


回答1:


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.




回答2:


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 ;



回答3:


Here is it

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 ;
} ;

output

1.000000 0x7fff89a7de80 0x7fff89a7de80 0x3ff0000000000000

2nd and 3rd addresses could be different. A shortcut

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

Cheers



来源:https://stackoverflow.com/questions/6575340/converting-double-to-void-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!