2

When I run the following code:

int i[] = {1,2,3};
int* pointer = i;
cout << i << endl;

char c[] = {'a','b','c','\0'};
char* ptr = c;
cout << ptr << endl;

I get this output:

0x28ff1c
abc

Why does the int pointer return the address while the char pointer returns the actual content of the array?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • 4
    Becuase of how cout works. cout recognizes ptr as a `char *` which cout treats as a null-terminated string, and thus prints out the contents instead of the pointer address. Cast ptr to `unsigned int` or `uintptr_t` too see the address... – Morten Jensen Nov 17 '15 at 13:16
  • 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) – Fabio says Reinstate Monica Nov 17 '15 at 14:00
  • Another very useful answer, with all the overloads for `operator <<` for `ostream`: http://stackoverflow.com/a/10869485/3982001 – Fabio says Reinstate Monica Nov 17 '15 at 14:05

3 Answers3

6

This is due to overload of << operator. For char * it interprets it as null terminated C string. For int pointer, you just get the address.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
1

The operator

cout <<

is overload 'char *' so it knows how to handle it (in this case, printing all chars till the end one).

But for int is not, so it just prints out the 'memory address'

Netwave
  • 40,134
  • 6
  • 50
  • 93
1

A pointer to char is the same type as a string literal. So for the sake of simplicity, cout will print the content of the char array as if it was a string. So when you are doing this:

cout << "Some text" << endl;

It does not print the address, the same way as your code is doing.

If you want to pring the address, cast it to size_t

cout << reinterpret_cast<size_t>(ptr) << endl;
BlackDwarf
  • 2,070
  • 1
  • 17
  • 22
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141