1

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

假装这是地址:0x00020348 假装这个地址的值是“delicious”

如何从地址 0x00020348 中获取字符串“delicious”?谢谢你。

4

1 回答 1

1

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

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

#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 部分- 然后我们获取整数“指针”并将其恢复为 aconst char* const以便它可以再次被视为 C 字符串。

第 4 部分- 最后我们std::string使用 C 字符串指针和字符串长度构造一个。由于 C 字符串是以空字符 ( ) 结尾的,因此您实际上并不需要字符串的长度,但是如果您必须自己在逻辑上计算出长度'\0',我将说明这种形式的构造函数。std::string

输出如下:

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

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

最后一点 - 对您的代码一无所知,void*通常认为 a 比 a 更好地表示通用指针int

于 2017-04-05T04:20:27.717 回答