c++ - 如何在 C++ 中初始化指向特定内存地址的指针

标签 c++ c pointers memory casting

关于这个的有趣讨论开始了here但是没有人能够提供 C++ 的做法:

#include <stdio.h>

int main(void)
{
  int* address = (int *)0x604769; 
  printf("Memory address is: 0x%p\n", address);

  *address = 0xdead; 
  printf("Content of the address is: 0x%p\n", *address);

  return 0;
}

在 C++ 中做这种事情最合适的方式是什么?

最佳答案

在 C++ 中,总是更喜欢 reinterpret_cast 而不是 C-cast。它是如此的丑陋,以至于有人会立即发现危险。

例子:

int* ptr = reinterpret_cast<int*>(0x12345678);

那东西伤了我的眼睛,我喜欢它。

关于c++ - 如何在 C++ 中初始化指向特定内存地址的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3934775/

相关文章:

c++ - 从 tcp 迁移到 udp 时,‘acceptor’ 不是 ‘boost::asio::ip::udp’ 的成员

c++ - 输出参数并通过引用传递

c - 在 C 中将 Char* 复制到 Char* 时遇到问题

c - void* 是否始终具有与 char* 相同的表示形式?

Cgicc.h 中的 C++ 类定义

c - rand() 在多个函数调用中是一致的

c - "void* p = &p;"在 C 中合法吗?

c - "Undefined reference to"同一文件中的 C 函数错误

C - 函数内结构数组的多个 malloc

python - 使用 C/API 和 C++ 类编写 Python 模块