【问题标题】:How to display address of a constant character pointer如何显示常量字符指针的地址
【发布时间】:2020-10-08 07:14:17
【问题描述】:

因为它可以用于整数和数值数据 当一个指针被创建并像这样显示时

int number = 5;
int *numberaddress = &number;
cout << "The number is "<< *numberaddress << endl;
cout << "The address of number is "<< numberaddress << endl;

但是,当对字符串或常量字符串指针执行相同操作时,它会给出字符串本身,如下所示

char string[20] = "string";
char *stringaddress = string;
const char *stringcopy = "string";
cout << "The string is " << stringaddress << endl;
cout << "The address of string is " << *stringaddress << endl;
cout << "The stringcopy is " << stringcopy << endl;

我怎样才能通过指针而不只是字符串来获取字符串的地址,有没有办法或者有不同的方法呢?

【问题讨论】:

  • 很确定这是一个骗子。基本上是std::cout &lt;&lt; (void*)stringaddress
  • 这能回答你的问题吗? Why is address of char data not displayed?
  • void* 在这里做什么...?我是 C++ 新手,请..

标签: c++ string pointers


【解决方案1】:

输出运算符&lt;&lt; 将所有指向char 的指针视为指向以空字符结尾的字符串的第一个字符的指针。

要打印地址本身,您需要将其转换为void*

cout << "The address of string is " << static_cast<void*>(stringaddress) << '\n';

注意*stringaddress 完全等于stringaddress[0],它是字符串中的第一个字符。

【讨论】:

  • @NumaanJaved static_cast&lt;void*&gt;(stringaddress)stringaddress 的类型从char* 转换为void*void* 类型是一个通用指针,它可以指向任何东西。更重要的是,它不会被视为指向以空字符结尾的字符串的第一个字符的指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 2013-08-24
  • 1970-01-01
  • 2013-08-02
  • 2020-12-30
  • 2020-07-27
相关资源
最近更新 更多