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. – Alexander Huszagh Sep 04 '19 at 02:58
  • 4
    The second example is undefined behavior because `< – 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
  • 31,330
  • 6
  • 30
  • 51
SoronelHaetir
  • 12,547
  • 1
  • 11
  • 21