简体   繁体   English

如何将指针转换为 int

[英]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:我试图将地址的值存储在非指针 int 变量中,当我尝试转换它时,我收到编译错误“从‘int*’到‘int’的无效转换”这是我正在使用的代码:

#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. int可能不足以存储指针。

You should be using intptr_t .您应该使用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 :你为什么要这样做,无论如何你只需要为 C 代码进行转换:

thatvalue = (int)ip;

If your writing C++ code, it is better to use reinterpret_cast如果你写 C++ 代码,最好使用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.我能够使用 C union 语句来实现您想要的。 It will of course be compiler dependent, but it worked for me like you would presume it should (Linux, g++).它当然依赖于编译器,但它对我有用,就像你认为它应该(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.在我的特定实例上,我的 int 是 32 位,指针是 48 位。 When assigning the pointer, the integer value i will represent the lowest 32 bit of the pointer.分配指针时,整数值 i 将代表指针的最低 32 位。

Since int *ip;由于int *ip; is a pointer to an integer and int thatvalue = 1;是一个指向整数和int thatvalue = 1;的指针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;是一个整数,假设要存储在由指向的地址的值ip分配给thatvalue ,变化thatvalue = ip; to thatvalue = *ip;thatvalue = *ip; (note the addition of the dereference operator * to access a value equivalent to the value at the pointer address ). (注意添加了取消引用运算符*以访问与指针地址处的等效的值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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