0
char a[] = {'k','l','m'};
cout << a << endl;

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

I run the above C++ code and here's the output:

klm
0x22fe00

I observe that char is the only primary type that has this behavior. Why this is happening? Are there any specialities of the char type?

2 Answers2

1

The name of an array often evaluates to the address of its first element. The standard output stream interprets character pointers as strings, and prints the data as a string. For integers, there is no such interpretation so you see the actual pointer value.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

The char[] is essentially how C and C++ treat strings of characters. The operator<< has been overloaded for the char[] to print out the values of the char array. On the other hand, arrays are essentially treated as constant pointers to their base element:

const int* p = &b[0];

Therefore, when you do cout << b << endl, you're actually printing out the base address of the array. That's why you get the hex number.

Bizkit
  • 384
  • 1
  • 10