如何从地址获取字符串?

How would get a string from an address?

本文关键字:字符串 获取 地址      更新时间:2023-10-16

我不确定如何从C++中的地址获取字符串。

假装这是地址:0x00020348 假装此地址包含值"美味">

如何从地址0x00020348中获取字符串"美味"? 谢谢。

这个答案是为了帮助扩展我们在评论中的对话。

请参考以下代码作为示例:

#include <stdio.h>
#include <string.h>
#include <string>
int main()
{
// Part 1 - Place some C-string in memory.
const char* const pszSomeString = "delicious";
printf("SomeString = '%s' [%08p]n", pszSomeString, pszSomeString);
// Part 2 - Suppose we need this in an int representation...
const int iIntVersionOfAddress = reinterpret_cast<int>(pszSomeString);
printf("IntVersionOfAddress = %d [%08X]n", iIntVersionOfAddress, static_cast<unsigned int>(iIntVersionOfAddress));
// Part 3 - Now bring it back as a C-string.
const char* const pszSomeStringAgain = reinterpret_cast<const char* const>(iIntVersionOfAddress);
printf("SomeString again = '%s' [%08p]n", pszSomeStringAgain, pszSomeStringAgain);
// Part 4 - Represent the string as an std::string.
const std::string strSomeString(pszSomeStringAgain, strlen(pszSomeStringAgain));
printf("SomeString as an std::string = '%s' [%08p]n", strSomeString.c_str(), strSomeString.c_str());
return 0;
}

第 1 部分- 变量pszSomeString应表示您尝试查找的内存中的实际字符串(一个任意值,但为了您的示例而0x00020348)。

第 2 部分- 您提到您将指针值存储为int,因此iIntVersionOfAddress是指针的整数表示。

第 3 部分- 然后我们获取整数"指针"并将其恢复为const char* const,以便可以再次将其视为 C 字符串。

第 4 部分- 最后,我们使用 C 字符串指针和字符串长度构造一个std::string。 您实际上不需要字符串的长度,因为 C 字符串是空字符 ('') 终止的,但我正在说明这种形式的std::string构造函数,以防您必须自己逻辑地计算长度。

输出如下:

SomeString = 'delicious' [0114C144]
IntVersionOfAddress = 18137412 [0114C144]
SomeString again = 'delicious' [0114C144]
SomeString as an std::string = 'delicious' [0073FC64]

指针地址会有所不同,但前三个十六进制指针值是相同的,正如预期的那样。 为std::string版本构造的新字符串缓冲区是一个完全不同的地址,正如预期的那样。

最后要注意 - 对您的代码一无所知,void*通常被认为是比int更好的泛型指针表示。