How do I cast a pointer to an int(如何将指针转换为 int)
问题描述
我试图将地址的值存储在非指针 int 变量中,当我尝试转换它时,我收到编译错误从‘int*’到‘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
可能不够大,无法存储指针.
int
may not be large enough to store a pointer.
您应该使用 intptr_t
.这是一个显式大到足以容纳任何指针的整数类型.
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).
这篇关于如何将指针转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将指针转换为 int
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01