0

I'm curious with this problem

int p[] = {1,2,3};
cout << p;

it will output address of the first element(1)
but.....

char p[] = {'a','b'};
cout << p;

it will not output the address of the first element but it will output the entire array "ab".
why does it happened ?

  • 2
    Likely because of how `std::cout` is overloaded for each. For the former, it's likely a general overload for arrays, that just outputs the address of the array. For the second, it's likely specialized since it's a string-like data type. – Alex Huszagh Sep 04 '19 at 02:58
  • 4
    The second example is undefined behavior because `<<` is expecting a null-terminated C-style string and your array is not null-terminated. – eesiraed Sep 04 '19 at 03:03

1 Answers1

2

The first will use std::basic_ostream<>::operator <<(const void *) which will just output the address. The second uses std::operator<<(std::basic_ostream<> &, const char *) which will output the character array just as if it were a string literal.

user4581301
  • 33,082
  • 7
  • 33
  • 54
SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23