使用cout输出字符串的地址

ostream类为下面的指针类型定义了插入运算符

  • const sighed char *
  • const unsighed char *
  • const char *
  • void *

所以cout语句都会直接显示字符串:

char name[20] = "Hello";
char * pn = "Hello";
cout << "Hello";
cout << name;
cout << pn;

cout方法使用字符串中的终止空字符来确定何时停止显示字符。
对于其他类型的指针,C++将其对应于 void *,并打印地址的数值表示。
所以如果想要获得字符串的地址,必须将其强制转换为 void * 类型或 int * 类型

const char * amount = "Hello";
// 显示字符串
cout << amount << endl;
// 显示字符串地址
cout << (void *)amount << endl;

打印出来如图:
在这里插入图片描述

你可能感兴趣的:(C/C++)