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?

user253751
  • 57,427
  • 7
  • 48
  • 90
  • USE gdb mate, for quick learning – ashish Dec 30 '15 at 06:14
  • 1
    Possible duplicate of [cout << with char\* argument prints string, not pointer value](http://stackoverflow.com/questions/17813423/cout-with-char-argument-prints-string-not-pointer-value) – Barmar Dec 30 '15 at 06:15

2 Answers2

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

user253751
  • 57,427
  • 7
  • 48
  • 90
  • What's your mean by operator << is overloaded specially for char pointers? – user3514850 Dec 30 '15 at 06:37
  • Do you know what operator overloading is? If so, then the explanation is clear. – PaulMcKenzie Dec 30 '15 at 06:42
  • I don't know operator overloading. Please explain a bit and give some link from where i can gain more knowledge. – user3514850 Dec 30 '15 at 06:46
  • @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. – user253751 Dec 30 '15 at 07:33
0

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

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621