Printing a pointer with <iostream> [duplicate]

荒凉一梦 提交于 2020-01-23 05:58:06

问题


Why does

#include <iostream>
using namespace std;

int main() {
  cout << (char*)0x10 << endl; 
}

segfault, but

#include <iostream>
using namespace std;

int main() {
  cout << (void*)0x10 << endl; 
}

seems to work just fine?


回答1:


Because

cout::operator <<(void*) 

prints a memory address, and

cout::operator <<(char*)

prints a null-terminated character array, and you run into undefined behaviour when you attempt to read the char array from 0x10.




回答2:


The ostream::operator<< is overloaded, there is a version for char* which interprets the given pointer as a null-terminated string.




回答3:


There's a special overload for << with char*, so that C-style strings can be output easily.

Thus

cout << (char*)0x10 << endl; 

tries to print out the string located at (char*)0x10 which is not memory it's supposed to look at.



来源:https://stackoverflow.com/questions/11749725/printing-a-pointer-with-iostream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!