Converting double to void* in C

后端 未结 3 1248
深忆病人
深忆病人 2020-11-30 14:24

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 a

相关标签:
3条回答
  • 2020-11-30 14:42

    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.

    0 讨论(0)
  • 2020-11-30 14:45

    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

    0 讨论(0)
  • 2020-11-30 14:51

    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 ;
    
    0 讨论(0)
提交回复
热议问题