将指针分配给字符串变量中包含的地址
Assigning a pointer to an address contained in a string variable
我有一个int* p1
和另一个字符串变量string addr
,其中包含p1
指向的地址(例如:" 0x5555b236df005"(。
我还有另一个指针int* p2
。如何分配p2
指向addr
中包含的地址(以指向与p1
指向相同位置的地址(?
这是我问题的非常简单的版本,因此执行p2 = p1
不是解决方案。
有办法做到这一点吗?如果是这样,如何?
您可以使用STD :: stringstream及其辅助功能STD :: hex((。
您的问题细节中有" 0x"的十六进制值...我不确定这是否会引起问题,但似乎并没有。
#include <string>
#include <iostream>
#include <sstream>
#include <assert.h>
int main()
{
int some_number = 42;
int* ptr1 = &some_number;
// convert a pointer to a string of hex digits
std::stringstream ss1;
ss1 << std::hex << ptr1;
std::string ptr1_as_hex = ss1.str(); // Note ptr_as_hex will not be pre-prepended with "0x"
ptr1_as_hex = "0x" + ptr1_as_hex;
// convert a string of hex digits to a pointer
// by way of a long long
long long ptr1_as_64bit_int;
std::stringstream ss2(ptr1_as_hex);
ss2 >> std::hex >> ptr1_as_64bit_int;
int* ptr2 = reinterpret_cast<int*>(ptr1_as_64bit_int);
assert(*ptr2 == 42);
return 0;
}
相关文章:
- 将数组的地址分配给变量并删除
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 为什么 Wild 指针包含零地址而不是 garabge 地址?
- C++:获取包含成员子对象的完整对象的地址
- 将指针分配给字符串变量中包含的地址
- C 如何使用包含浮点的CE的给定地址进行阅读/写入
- 返回类型 char* 的成员函数返回在 while 循环后包含不同字符串的地址
- [C ] NULL确实在内存中也包含一个特定的地址
- 检查子对象的地址是否在包含对象的边界内是否合法
- 为什么此指针包含存储在堆上的地址
- 反转指向成员的指针(即获取包含结构的地址)
- 复制包含原子成员的对象的地址
- std矢量包含指针和变量地址.清理
- 我想知道指针在调试时包含特定的地址
- 在另一个函数内部改变指针数组所包含的地址
- 是否可以从FTP地址添加包含路径到visual studio ?
- 为什么变量指针包含相同数据类型的地址?
- 包含值地址的字符串 ->该值的指针
- 包含地址的排序向量
- 使类指针指向包含其成员的地址