0

If we declare:

int i; 
int *ptr1 = &i;
*ptr1=10;
cout << ptr1;

Here ptr1 will give the address. But:

char *ptr2;
ptr2="Priyesh";
cout << ptr2;

Here it will give the content of the character pointer. Why is there such a difference?

2

2 Answers 2

5

operator << is overloaded specially for char pointers - the assumption is that if you try to print a char pointer, you actually want to print the string it points to.

If you want to print it the same way as any other pointer, cast it to void* first:

char *ptr2;
ptr2="Priyesh";
cout << static_cast<void*>(ptr2);

(or cout << (void*)ptr2;)

Sign up to request clarification or add additional context in comments.

4 Comments

What's your mean by operator << is overloaded specially for char pointers?
Do you know what operator overloading is? If so, then the explanation is clear.
I don't know operator overloading. Please explain a bit and give some link from where i can gain more knowledge.
@user3514850 Imagine it was a print function instead of <<... then there would be separate print(const char*) and print(const void*) functions. And if you did print(p) it would call the first one if p was a pointer to char, and the second one if it was any other kind of pointer.
0

Because there's an operator<< overload that specifically takes a const char* argument to print it as a string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.