char *ps;
ps = &anotherChar;
cout << ps;
Why this displays the value of anotherChar not just the address?.
char *ps;
ps = &anotherChar;
cout << ps;
Why this displays the value of anotherChar not just the address?.
The operator << assumes you want to print the string not the address of the string.
Since ps points to the string, if you want to print the address of ps use "<< &ps"
There is an operator<<
overload for char *
which interprets it as a string to be output. If you want an address, you could to cast to void*
.
Because char*'s are c-style strings. It does what it thinks you want, which is print out the c-string pointed to at ps.
You could print the address with:
cout << static_cast<void*>(ps) << endl;
The reason why is that a char*
in C/C++ is a dual purposed type. It can be both a pointer to a single character or a C style string. The cout function chooses to treat this as a C style string and hence will print the values instead of the address.
This is also a potential problem for your application. C style strings end with a null terminator value. Hence this has the potential to read illegal memory since it's not properly initialized.
The << operator has numerous overloads for working with streams.
One of these prints a zero terminated string for you. The type of the variable used to point to a zero terminated string is a char*. This is what you've used. If you wrote:
char* ps = "hello";
cout << ps;
This overload would print "hello". It's probably just luck that there is a zero in memory after anotherChar so that the overload of the << stops printing characters after printing anotherChar. There is a good chance that if this isn't a zero you'd print out random characters from memory until a zero was encountered.
C++ does not have a built in type for strings. It uses a null terminated (array that ends in '\0') char *
(plus or minus const qualifiers) or char []
as a convention to represent strings. All the Standard C libraries use this convention.
So, the STL ostreams
also use this convention.