首页 > 解决方案 > 如何显示常量字符指针的地址

问题描述

像这样创建和显示指针时,可以对整数和数值数据执行此操作

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;

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

标签: c++stringpointers

解决方案


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

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

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

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


推荐阅读