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?
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?
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)
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;
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;
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
© 2022 - 2024 — McMap. All rights reserved.
&p
equates to achar*
, and the<<
operator has a special overload to treatchar*
as a null-terminated C-string. – Rozprintf("%p\n", (void *)pointer);
– Shoemaker