c++ - 使用地址值初始化指针

标签 c++ c pointers

我需要用已知的地址初始化一个指针变量。请看下面的代码,ptr是最终目的地,ptr_address的值包含地址值,所以我需要做类似ptr = value的操作。

int *ptr;
int address;

address = 0x10000005;
ptr = address;

问题是编译器给出以下警告消息:

warning: assignment makes pointer from integer without a cast [enabled by default]

我的代码是错误的还是有其他方法可以在不收到此编译器警告的情况下执行此操作?

最佳答案

使用强制转换:

intptr_t some_variable = 25;

int * ptr1 = (int *) 0x10000005;
int * ptr2 = (int *) some_variable;

或者在 C++ 中:

int * ptr1 = reinterpret_cast<int *>(0x10000005);
int * ptr2 = reinterpret_cast<int *>(some_variable);

关于c++ - 使用地址值初始化指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20815806/

相关文章:

c++ - 使用指针而不是引用时出现段错误访问指向结构的指针数组

c++ - 出于某种原因,串行代码比 SIMD 代码运行得更快

c++ - 使用可变数量的 std::thread 的引用问题

java - 将 submat 从 RGB 转换为 GRAY OpenCV

c++ - 轻松测量耗时

c - strcmp 不做比较

c++ - 指针运算是否适用于迭代器?

c++ - 将表达式缩写为标识符

c - 服务器回显时套接字编程错误

c - 访问具有结构指针的结构中的整数