pointer to characters...

Take for example the following

char* p=new char[5] //give mem address of size 5 * size char to p

strcpy (p, "Hi");

cout<<p<<endl; gives Hi

How come cout<<p<<endl; gives Hi without cout<<*p<<endl; because p holds memory address and *p deferences that means gives the value?
Last edited on
This is tricky because p actually points to the 'H' in your string. So if you were to print *p, it would only output 'H', since that's what p points to.

normally when you output a pointer, it would print the memory address, as you think. However, char pointers are treated like a special case. For char pointers, instead of printing the address, it will treat the pointer as if it points to string data, and will follow the pointer and print all the data it points to (until it finds the null terminator).



So yeah -- you are right to be confused. It's a special case.
thanks!
Topic archived. No new replies allowed.