【问题标题】:C++ pointer casting not workingC ++指针转换不起作用
【发布时间】:2016-10-27 09:19:00
【问题描述】:

我做错了什么,消息框中的值不同。这是在 Windows 上的 32 位应用程序中。我读过的所有内容都说 reinterpret_cast 不应该是必要的,即使我尝试它仍然不起作用。还尝试了更大的数据类型来保存指针,但从我读到的内容来看,在 32 位 int 或 DWORD 上应该没问题。

A* a_ptr;    

DWORD a_ptr_address = (DWORD)a_ptr;
A* a_recasted_ptr = (A*)a_ptr_address;

//Display Result
char debugString[20];
snprintf(debugString, 20, "%08x", &a_ptr);
MessageBox(NULL, (const char*)debugString, NULL, NULL);
snprintf(debugString, 20, "%08x", &a_recasted_ptr);
MessageBox(NULL, (const char*)debugString, NULL, NULL);

【问题讨论】:

  • 首先,a_ptr 指向垃圾,所以这已经是 UB。
  • 你打印指向指针的指针,而不是指针本身。

标签: c++ pointers memory casting


【解决方案1】:

您正在显示两个不同变量 a_ptr 和 a_recasted_ptr 的地址。它们不在同一个地址存储器中。
删除snprintf() 调用中的&,就完成了。

不过,代码还是很糟糕...
试试这个:

A a;
A* a_ptr=&a;

SIZE_T a_ptr_address = (SIZE_T)a_ptr;
A* a_recasted_ptr = (A*)a_ptr_address;

//Display Result
char debugString[20];
snprintf(debugString, 20, "%0p", a_ptr);
MessageBoxA(NULL, debugString, NULL, NULL);
snprintf(debugString, 20, "%0p", a_recasted_ptr);
MessageBoxA(NULL, debugString, NULL, NULL);

【讨论】:

  • 这行得通,谢谢。对于糟糕的代码感到抱歉,我已经重写了很多次试图让它工作,但它变得很hacky。
【解决方案2】:
  1. 将 MessageBox 替换为 MessageBoxA 并删除 (const char*) 强制转换。

  2. 在此示例中,您有 3 个不同的变量:a_ptr、a_ptr_address 和 a_recasted_ptr。 由于您有 3 个变量,因此它们具有不同的地址,因为它们是不同的变量。但是,它们的值可以相同。 例如,a_ptr 和 a_recasted_ptr 的地址不同,但值相同。 在您的示例中,您显示的是变量的地址,而不是它们的值。

固定的可能版本:

struct A {};
// assign some dummy value to a_ptr
A* a_ptr = (A*)0x00000007;

DWORD_PTR a_ptr_address = (DWORD_PTR)a_ptr;
A* a_recasted_ptr = (A*)a_ptr_address;

//Display Result
char debugString[40];
sprintf_s(debugString, "Value of %08x=%u", &a_ptr, (DWORD_PTR)a_ptr);
MessageBoxA(NULL, debugString, NULL, NULL);
sprintf_s(debugString, "Value of %08x=%u", &a_recasted_ptr, (DWORD_PTR)a_recasted_ptr);
MessageBoxA(NULL, debugString, NULL, NULL);

编辑:根据 cmets 修复错误

【讨论】:

  • 不是 dv,但这会产生编译错误,您可能需要检查一下。
  • 还值得指出的是,DWORD 不一定大到足以容纳指针。 OP 可能需要使用 DWORD_PTR。
猜你喜欢
  • 2015-08-15
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 2021-06-06
  • 2021-09-20
相关资源
最近更新 更多