将指针分配给字符串变量中包含的地址

Assigning a pointer to an address contained in a string variable

本文关键字:包含 地址 变量 字符串 指针 分配      更新时间:2023-10-16

我有一个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;
}