1
#include <iostream>

int main ()
{
    using std::cout; 

    char example1[] = "John";
    int  example2[] = {1,2,3,4};

    cout << example1 << endl;
    cout << example2 << endl;
}

The output of the program is as follows -

John   
0x7fff50e079b0

Why is the first print statement returning the entire string and the second one just the address of the first element?

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    Because that's how `cout` was designed. `char` pointers are commonly used as strings in C, and sometimes you want to use them as strings even in C++. – HolyBlackCat Jan 22 '20 at 22:25
  • Both return pointer. << operator probably overloaded for char *. If you want to see the address you can try to print `reinterpret_cast(example1)`. It will interpret the byte pattern as void * instead of char *. – bca Jan 22 '20 at 22:26
  • 2
    @thoron `static_cast` would be more appropriate than `reinterpret_cast`. But yes, you are correct that `operator<<` is overloaded to treat `char*` as a null-terminated C string, so a cast to `void*` is needed if you want to print the address the pointer holds rather than the data the pointer is pointing at. – Remy Lebeau Jan 22 '20 at 22:33

0 Answers0