Why C++ would not print the memory address of a char but will print int or bool?(为什么 C++ 不会打印 char 的内存地址,但会打印 int 或 bool?)
问题描述
可能重复:
为什么char数据的地址不显示?
这是代码和输出:
int main(int argc, char** argv) {
bool a;
bool b;
cout<<"Address of a:"<<&a<<endl;
cout<<"Address of b:"<<&b<<endl;
int c;
int d;
cout<<"Address of c:"<<&c<<endl;
cout<<"Address of d:"<<&d<<endl;
char e;
cout<<"Address of e:"<<&e<<endl;
return 0;
}
输出:
a:0x28ac67的地址
Address of a:0x28ac67
b的地址:0x28ac66
Address of b:0x28ac66
c:0x28ac60的地址
Address of c:0x28ac60
d:0x28ac5c的地址
Address of d:0x28ac5c
e的地址:
我的问题是:char的内存地址在哪里?为什么不打印?
My question is: Where is the memory address of the char? And why is it not printed?
谢谢.
推荐答案
我怀疑 ostream::operator
char *
的版本ostream::operator<<
需要一个以 NUL 结尾的 C 字符串 - 并且您只传递一个字符的地址,所以您在这里拥有的是未定义的行为.您应该将地址转换为 void *
以使其打印您期望的内容:
I suspect that the overloaded-to-char *
version of ostream::operator<<
expects a NUL-terminated C string - and you're passing it only the address of one character, so what you have here is undefined behavior. You should cast the address to a void *
to make it print what you expect:
cout<<"Address of e:"<< static_cast<void *>(&e) <<endl;
这篇关于为什么 C++ 不会打印 char 的内存地址,但会打印 int 或 bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 C++ 不会打印 char 的内存地址,但会打印 int 或 bool?


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01