tags:

views:

680

answers:

7
char *ps;
ps = &anotherChar;
cout << ps;

Why this displays the value of anotherChar not just the address?.

+3  A: 

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"

Martin Beckett
Why it 'assumes'?
Loai Najati
Because 9/10 when you want to print a string you want the contents of the string - not the address in memory.
Martin Beckett
Thanks. I really appreciate that.
Loai Najati
+13  A: 

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*.

crashmstr
If I remember correctly, casting to void* will print the address in hexadecimal by default.
OregonGhost
Why exactly there's an operator overloading for this type?
Loai Najati
Generally, when you have a char*, it is a `C` style string and most functions will treat it as such. In this case, it allows for the stream class to output `C` strings as text.
crashmstr
+2  A: 

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;
Todd Gardner
+5  A: 

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.

JaredPar
How can this be a C style string?!. The C style string is the array of char.
Loai Najati
+1  A: 

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.

Scott Langham
+1  A: 

If you want the pointer value:

cout << (void *) ps;
anon
A: 

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.

MSN