How do I cast a pointer to an int

感情迁移 提交于 2020-05-10 08:45:50

问题


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 is the code I'm using:

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

vector<int> test;

int main() {
    int *ip;
    int pointervalue = 50;
    int thatvalue = 1;

    ip = &pointervalue;
    thatvalue = ip;

    cout << ip << endl;

    test.push_back(thatvalue);

    cout << test[0] << endl;
    return 0;
}

回答1:


int may not be large enough to store a pointer.

You should be using intptr_t. This is an integer type that is explicitly large enough to hold any pointer.

    intptr_t thatvalue = 1;

    // stuff

    thatvalue = reinterpret_cast<intptr_t>(ip);
                // Convert it as a bit pattern.
                // It is valid and converting it back to a pointer is also OK
                // But if you modify it all bets are off (you need to be very careful).



回答2:


You can do this:

int a_variable = 0;

int* ptr = &a_variable;

size_t ptrValue = reinterpret_cast<size_t>(ptr);



回答3:


I'd suggest using reinterpret_cast:

thatvalue = reinterpret_cast<intptr_t>(ip);



回答4:


Why are you trying to do that, anyway you just need to cast, for C code :

thatvalue = (int)ip;

If your writing C++ code, it is better to use reinterpret_cast



来源:https://stackoverflow.com/questions/14092754/how-do-i-cast-a-pointer-to-an-int

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