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::operatorchar * 的版本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?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
