Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c++ - How do I cast a pointer to an int

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...