简体   繁体   中英

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

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

You can do this:

int a_variable = 0;

int* ptr = &a_variable;

size_t ptrValue = reinterpret_cast<size_t>(ptr);

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

我建议使用reinterpret_cast

thatvalue = reinterpret_cast<intptr_t>(ip);

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.

Since int *ip; is a pointer to an integer and int thatvalue = 1; is an integer, assuming you want the value stored at the address pointed to by ip assigned to thatvalue , change thatvalue = ip; to thatvalue = *ip; (note the addition of the dereference operator * to access a value equivalent to the value at the pointer address ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM