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?
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?
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.
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;
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);
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.