Why C++ would not print the memory address of a char but will print int or bool? [duplicate]

人盡茶涼 提交于 2019-12-04 00:38:43

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;

Strings in C/C++ can be represented by char*, the same type as &e. So the compiler thinks you're trying to print a string. If you want to print the address, you could cast to void*.

std::cout << static_cast<void *>(&e) << std::endl;
Benjamin Trent

Check out this previously asked question: Why is address of char data not displayed?

Also, if you utilize printf("Address of e: %p \n", &e); that will work as well.

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