如何从地址获取字符串?
How would get a string from an address?
我不确定如何从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
更好的泛型指针表示。
相关文章:
- 从C字符串中获取奇怪的字符串长度
- 获取字符串的长度并将其分配给数组
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 调用CreateProcess()并获取字符串的返回值
- 从字符串中获取结构的大小
- Cryptopp:获取密码输入的填充字符串
- 获取无效的字符串大小
- 获取 OID(类型::b_oid)作为 MongoDB C++驱动程序中的字符串
- C ++编译器如何获取argv字符串的长度
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 如何使用字符串获取用户控制台输入
- 通过字符串获取小部件
- 无法从字符串获取数字输入
- 在C++的静态方法中将类名作为字符串获取
- 从设备实例路径字符串获取设备实例 DWORD
- HRESULT到字符串(获取文档路径)C++
- 如何从http请求体字符串获取文件名
- 如何使用带有垃圾字符的子字符串获取字符串
- 通过字符串获取对话框项的可能性
- 有没有办法将 WinAPI 错误标志作为字符串获取