如何将变量的内容存储到const char*中

how to store the content of variable into const char*?

本文关键字:const char 存储 变量      更新时间:2023-10-16

我有一个存储地址的指针或变量,如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";
}

或者,如果你不喜欢魔术数字,希望你的代码即使在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 '' terminator
  snprintf(buf,N,"%p",ptr);
  std::cout << "pointer as string: " << buf << "n";
  std::cout << "pointer as value: " << static_cast<void*>(ptr) << "n";
}

Ideone示例

好的,假设必须有一些额外的参数来告诉函数实际传递的数据类型,但是您可以这样做:

extern void afunc(const char *p, int type);
int value = 1234;
afunc((const char *)&value, TYPE_INT);

你看过const_cast了吗?它是一种在c++中添加/删除变量的const-ness的方法。请看这里。