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?
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With