如何将指针强制转换为int

时间:2012-12-30 17:15:06

标签: c++ pointers casting

我正在尝试将地址的值存储在非指针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;
}

6 个答案:

答案 0 :(得分:9)

int可能不够大,无法存储指针。

您应该使用intptr_t。这是一个显式大到足以容纳任何指针的整数类型。

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

答案 1 :(得分:5)

你可以这样做:

int a_variable = 0;

int* ptr = &a_variable;

size_t ptrValue = reinterpret_cast<size_t>(ptr);

答案 2 :(得分:2)

为什么你要这样做,无论如何你只需要施放,为C代码:

thatvalue = (int)ip;

如果您编写C ++代码,最好使用reinterpret_cast

答案 3 :(得分:2)

我建议使用reinterpret_cast

thatvalue = reinterpret_cast<intptr_t>(ip);

答案 4 :(得分:0)

我能够使用 C union 语句来实现您想要的。它当然取决于编译器,但它对我有用,就像你认为它应该(Linux、g++)一样。

union {
    int i;
    void *p;
} mix;

mix.p = ip;
cout << mix.i << endl;

在我的特定实例上,我的 int 是 32 位,指针是 48 位。分配指针时,整数值 i 将代表指针的最低 32 位。

答案 5 :(得分:0)

由于 int *ip; 是一个指向整数的指针,而 int thatvalue = 1; 是一个整数,假设您希望将值存储在 指向的地址 ip 分配为thatvalue,将thatvalue = ip;更改为thatvalue = *ip;(注意添加了dereference operator * 以访问与指针地址处的值等价的值).