How do I cast a pointer to an int

后端 未结 5 2145
一向
一向 2021-02-13 21:54

I\'m trying to store the value of an address in a non pointer int variable, when I try to convert it I get the compile error \"invalid conversion from \'int*\' to \'int\'\" this

5条回答
  •  悲&欢浪女
    2021-02-13 22:57

    I was able to use the C union statement to achieve what you were looking for. It will of course be compiler dependent, but it worked for me like you would presume it should (Linux, g++).

    union {
        int i;
        void *p;
    } mix;
    
    mix.p = ip;
    cout << mix.i << endl;
    

    On my particular instance my int is 32 bit and the pointer is 48 bit. When assigning the pointer, the integer value i will represent the lowest 32 bit of the pointer.

提交回复
热议问题