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
  • 36,309
  • 8
  • 69
  • 115
  • 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 < – 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
  • 23,407
  • 6
  • 45
  • 84
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
  • 36,219
  • 6
  • 36
  • 71
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,060
  • 1
  • 15
  • 21
Guillaume Racicot
  • 36,309
  • 8
  • 69
  • 115