Reputation: 21
assume
char a='s';
now i want to store the address of variable a in char pointer p
char *p=&a;
if i use cout << p;
then i get the value s, not the address!
can anyone explain the reason why is it so?
Upvotes: 2
Views: 525
Reputation: 6844
Calling cout << p
is type safe ( C++ objects and operators ) so it uses a operator for char *. This operator serves to print the strings saved in the char pointer. It takes the address and prints everything from start to the first occurrence of byte zero. If you are using MS windows then it is probably only this one char because this system zeros the memory so zero byte is soon. If you want to print the address then try cout << (void *)p;
Upvotes: 1
Reputation: 13692
As many answers above tell you, << operator is overloaded to handle char* as C type string i.e NULL terminated array of characters. In your case when you print p, it gets treated as C string and all the characters till first NULL character are printed. If you only get s printed then there is a NULL character immediately next to your variable a in memory. But this behavior may change depending on the memory contents. I guess you are declaring a as a global variable because space for global variables is usually initialized to all zeros.
Also it will be an interesting experiment for you to declare two character variables and then cout there pointer the same way as you have above. My guess is that pointer to first variable will print both of them.
Upvotes: 0
Reputation: 29164
In C a char*
is typically used to point to the beginning of a (null-terminated) string. In order to make C++ IO streams (such as cout
) compatible with this habit, there's an overloaded verion of operator<<()
for handling char
pointers. This operator just prints out the null-terminated string starting at the given address.
If you want to print out the 'value' of the pointer (note that it is not part of the C/C++ standard what a pointer 'looks like'), cast the pointer to void*
such as
std::cout << static_cast<void*>(charpointer);
Upvotes: 0
Reputation: 523294
The basic_ostream
's <<
operator is specialized for const char*
arguments*, to output it like a C string**. See the answer to Why does cout print char arrays differently from other arrays? for more detail.
Basically, you could cast p
to void*
when printing to get the address.
cout << static_cast<void*>(p);
*: Also const charT*
where charT
is the character type adopted by the basic_ostream
, and const unsigned char*
and const signed char*
if the charT == char
. For example, wcout
would treat a const wchar_t*
as a (wide) C string, but cout
would treat it as a pointer.
**: This is overiddable by the character traits used by that basic_ostream
. See C++ standard §[ostream.inserters.character]/4 for the detailed algorithm.
Upvotes: 8
Reputation: 2947
In C/C++ a pointer to char normally is used as a pointer to a null-terminated string. The << operator handles this common use case.
Upvotes: -1