"cout" and "char address" [duplicate]
Asked Answered
O

3

11
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?

Orthocephalic answered 21/3, 2015 at 22:12 Comment(2)
&p equates to a char*, and the << operator has a special overload to treat char* as a null-terminated C-string.Roz
printf is much more elegant here. printf("%p\n", (void *)pointer);Shoemaker
S
14

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)
Selfmade answered 21/3, 2015 at 22:15 Comment(0)
N
6

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.

Nettienetting answered 21/3, 2015 at 22:17 Comment(0)
J
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

Jotunheim answered 21/3, 2015 at 22:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.