gpt4 book ai didi

c++ - 如何将变量的内容存入const char*?

转载 作者:行者123 更新时间:2023-11-28 03:50:15 25 4
gpt4 key购买 nike

我有一个指针或变量来存储像 0xb72b218 这样的地址,现在我必须将这个值存储到 const char* 中。我如何存储它。提前致谢。我试过以下:假设我有一个指针变量“ptr”,其中包含 0xb72b218

ostringstream oss;
oss << ptr;
string buf = oss.str();
const char* value = buf.c_str();

但任何人都知道简单的方法更复杂。

最佳答案

好吧......如果你真的想要字符串中某物的地址,这会做:

#include <stdio.h>
#include <iostream>

int main(){
char buf[30];
void* ptr = /*your pointer here*/;
snprintf(buf,sizeof(buf),"%p",ptr);

std::cout << "pointer as string: " << buf << "\n";
std::cout << "pointer as value: " << ptr << "\n";
}

或者,如果您不喜欢魔数(Magic Number),并且希望您的代码即使在 256 位指针不再特别的情况下也能正常工作,请尝试以下操作:

#include <limits>  // for numeric_limits<T>
#include <stdint.h> // for intptr_t
#include <stdio.h> // for snprintf
#include <iostream>

int main(){
int i;
int* ptr = &i; // replace with your pointer
const int N = std::numeric_limits<intptr_t>::digits;
char buf[N+1]; // +1 for '\0' terminator
snprintf(buf,N,"%p",ptr);

std::cout << "pointer as string: " << buf << "\n";
std::cout << "pointer as value: " << static_cast<void*>(ptr) << "\n";
}

Example on Ideone .

关于c++ - 如何将变量的内容存入const char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5790165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com