如何从地址中获取字符串?

How would get a string from an address?

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

假设这是地址:0x00020348 假装此地址包含值 "delicious"

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

此回答有助于扩大我们在评论中的对话。

请看下面代码为例:

#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 部分 - 然后我们取整数 "pointer" 并将其恢复为 const char* const 以便再次将其视为 C 字符串.

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

输出结果如下:

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

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

最后说明 - 对您的代码一无所知,void* 通常被认为是比 int.

更好的通用指针表示形式