4 c++
说我有一个对象
MyObj stuff;
Run Code Online (Sandbox Code Playgroud)
为了得到东西的地址,我会打印
cout << &stuff << endl; 0x22ff68
Run Code Online (Sandbox Code Playgroud)
我想在字符串中保存0x22ff68.我知道你不能这样做:
string cheeseburger = (string) &stuff;
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这个目标?
这是一种将指针的地址保存为字符串然后将地址转换回指针的方法。我这样做是作为概念证明,const并没有真正提供任何保护,但我认为它很好地回答了这个问题。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
// create pointer to int on heap
const int *x = new int(5);
// *x = 3; - this fails because it's constant
// save address as a string
// ======== this part directly answers your question =========
ostringstream get_the_address;
get_the_address << x;
string address = get_the_address.str();
// convert address to base 16
int hex_address = stoi(address, 0, 16);
// make a new pointer
int * new_pointer = (int *) hex_address;
// can now change value of x
*new_pointer = 3;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用字符串格式
char strAddress[] = "0x00000000"; // 注意:你应该分配正确的大小,这里我假设你使用的是32位地址
sprintf(strAddress, "0x%x", &stuff);
然后使用普通的字符串构造函数从此 char 数组创建字符串
| 归档时间: |
|
| 查看次数: |
5327 次 |
| 最近记录: |