c++ - 如何显示常量字符指针的地址
问题描述
像这样创建和显示指针时,可以对整数和数值数据执行此操作
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;
我怎样才能通过指针而不只是字符串来获取字符串的地址,有没有办法或者有不同的方法呢?
解决方案
输出运算符<<
将所有指向char
的指针视为指向以空字符结尾的字符串的第一个字符的指针。
要打印地址本身,您需要将其转换为void*
:
cout << "The address of string is " << static_cast<void*>(stringaddress) << '\n';
请注意,*stringaddress
它完全等于stringaddress[0]
,它是字符串中的第一个字符。
推荐阅读
- python-3.x - 如何将数据框中的列绘制为子图
- python-3.x - 每隔一小时更新一次频率
- c# - 将类型列表gameObjects添加到GameObject列表时获取null
- python - python fabric run() sudo 命令不提示输入密码
- sharepoint - 具有 4 个条件的 CAML 查询将引发此错误“无法完成此操作。\n\n请重试。”
- python - Web Scraping 问题,使用 BeautifulSoup 库返回空列表
- c# - 如何统一停止触发动画?
- javascript - 带切换的响应式垂直/水平标题表
- javascript - 我究竟做错了什么?从下拉列表中获取选择。Javascript
- javascript - 如何使用jQuery将jsp文件包含在另一个jsp文件中