如何将指针强制转换为int

use*_*608 5 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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 10

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).
Run Code Online (Sandbox Code Playgroud)


sga*_*zvi 8

你可以这样做:

int a_variable = 0;

int* ptr = &a_variable;

size_t ptrValue = reinterpret_cast<size_t>(ptr);
Run Code Online (Sandbox Code Playgroud)

  • 使用`<cstdint>`中的`std :: uintptr_t`. (7认同)
  • size_t可能会起作用.但是`intptr_t`被明确地设计为一个可以保存指针值的整数(不会丢失信息). (3认同)