Why does streaming a char pointer to cout not print an address?
Solution 1:
Overload resolution selects the ostream& operator<<(ostream& o, const char *c);
which is used for printing C-style strings. You want the other ostream& operator<<(ostream& o, const void *p);
to be selected. You are probably best off with a cast here:
cout << static_cast<void *>(cptr) << endl;
Solution 2:
cout
prints a string if it receives a char *
, simple as that.
Here are the overloads for operator <<
for ostream
:
ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (const void* val);
ostream& operator<< (streambuf* sb);
ostream& operator<< (ostream& ( *pf )(ostream&));
ostream& operator<< (ios& ( *pf )(ios&));
ostream& operator<< (ios_base& ( *pf )(ios_base&));
ostream& operator<< (ostream& out, char c );
ostream& operator<< (ostream& out, signed char c );
ostream& operator<< (ostream& out, unsigned char c );
//this is called
ostream& operator<< (ostream& out, const char* s );
ostream& operator<< (ostream& out, const signed char* s );
ostream& operator<< (ostream& out, const unsigned char* s );
If you want the address, you want:
ostream& operator<< (const void* val);
so you need to cast to const void*
.