Kor*_*gay 12 c++ char memory-address
可能重复:
为什么不显示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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
地址a:0x28ac67
地址b:0x28ac66
地址c:0x28ac60
地址d:0x28ac5c
地址:
我的问题是:char的内存地址在哪里?为什么不打印?
谢谢.
Cha*_*ton 16
C/C++中的字符串可以表示为char*与...相同的类型&e.所以编译器认为你正在尝试打印一个字符串.如果要打印地址,可以转换为void*.
std::cout << static_cast<void *>(&e) << std::endl;
Run Code Online (Sandbox Code Playgroud)
小智 11
我怀疑重载到char *版本ostream::operator<<期望一个NUL终止的C字符串 - 而你只传递一个字符的地址,所以你在这里有未定义的行为.您应该将地址转换为a void *以使其打印出您期望的内容:
cout<<"Address of e:"<< static_cast<void *>(&e) <<endl;
Run Code Online (Sandbox Code Playgroud)