“cout” and “char address” [duplicate]

☆樱花仙子☆ 提交于 2019-12-21 16:48:58

问题


char p;
cout << &p;

This does not print the address of character p. It prints some characters. Why?

char p;
char *q;
q = &p;
cout << q;

Even this does not. Why?


回答1:


I believe the << operator recognizes it as a string. Casting it to a void* should work:

cout << (void*)&p;

std::basic_ostream has a specialized operator that takes a std::basic_streambuf (which basically is a string (in this case)):

_Myt& operator<<(_Mysb *_Strbuf)

as opposed to the operator that takes any pointer (except char* of course):

_Myt& operator<<(const void *_Val)



回答2:


This is because the pointer to char has its own overload of <<, which interprets the pointer as a C string.

You can fix your code by adding a cast to void*, which is the overload that prints a pointer:

char p;
cout << (void*)&p << endl;

Demo 1.

Note that the problem happens for char pointer, but not for other kinds of pointers. Say, if you use int instead of char in your declaration, your code would work without a cast:

int p;
cout << &p << endl;

Demo 2.




回答3:


std::cout will treat a char* as a string. You are basically seeing whatever is contained in memory at the location of your uninitialised pointer - until a terminating null character is encountered. Casting the pointer to a void* should print the actual pointer value if you need to see it



来源:https://stackoverflow.com/questions/29188668/cout-and-char-address

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