Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"cout" and "char address" [duplicate]

Tags:

c++

char

cout

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?

like image 760
GandalfDGrey Avatar asked Mar 21 '15 22:03

GandalfDGrey


3 Answers

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.

like image 183
Sergey Kalinichenko Avatar answered Oct 29 '22 15:10

Sergey Kalinichenko


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)
like image 14
Andreas Vennström Avatar answered Oct 29 '22 17:10

Andreas Vennström


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

like image 3
mathematician1975 Avatar answered Oct 29 '22 16:10

mathematician1975