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?
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?
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;)
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.Because there's an operator<< overload that specifically takes a const char* argument to print it as a string.