C-string pointer

Hello, in the block of code below, ptr is a pointer to a C-string. It should store the memory address of the first element, if I understand correctly. Why does it print out "hello" when I try to print the ptr itself? Shouldn't it be a memory address? Thank you very much for explaining.

1
2
3
4
5
6
7
8
9
10
  int main()
{
	char mychar[] = "hello";
	char * ptr = mychar;
	cout << ptr << endl;  //hello

	cout << *ptr << endl;  //h

	cin.get();
}
char * is a known type for the stream and is printed accordingly. Change char -> void and you will see the address.
The behaviour that you do expect would be by:
ostream& ostream::operator<< ( void* );
http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/

However, there is also:
ostream& operator<< ( ostream& os, const char* );
http://www.cplusplus.com/reference/ostream/ostream/operator-free/

and const char* is closer match for char* than the void*.


If you do wan't to show the address of a char pointer, then cast:
cout << static_cast<void*>(ptr) << endl;
Topic archived. No new replies allowed.