character pointers in C++

If you want to print the address, then you've to cast the char* to void*, as

const char *str = "how are you\n"; 
cout << (void*) str << endl; 

In the absense of the cast, cout sees str as const char* (which in fact it is) and so cout thinks you intend to print the null-terminated char string!

Think : if you want coud << str to print the address, how would you print the string itself?

--

Anyway here is more detail explanation:

operator<< is overloaded for char* as well as void* :

//first overload : free standing function
basic_ostream<char, _Traits>& operator<<(basic_ostream<char, _Traits>& _Ostr, const char *_Val);

//second overload : a member of basic_ostream<>
_Myt& operator<<(const void *_Val);

In the absence of the cast, first overload gets called, but when you cast to void*, second overload gets called!


This is due to Operator overloading.

the << operator is overloaded to output the string pointed to by the character pointer.

Similarly, with *p, you will get the first character, hence you get the first character as output.


The cout << str << endl; prints "how are you", because str is char *, which is treated as a string.

The cout << i << endl; prints 0xbfac1eb0, because i is a int [], which is treated as int*, which is treated as void*, which is a pointer.

The cout << *str << endl' prints "h" because *str is a char with value of 'h'.

Tags:

C++

Pointers