-2

I have come across a c++ code:

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;

output: Hello

Since greeting is an array of size 6, displaying greeting should display only "H" because of greeting[0] in cout, since it is displaying first address of array. I don't know where I am wrong.

Ali Seyedi
  • 1,718
  • 1
  • 19
  • 24

4 Answers4

7

Except when it is the operand of the sizeof or unary & operators, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

This means that in the statement

cout << greeting << endl;

the expression greeting is converted from an expression of type char [6] to an expression of type char *, and the value of the expression is the address of the first element.

The stream operator << is defined such that if it receives an argument of type char *, it will write out the sequence of characters starting at that address until it sees the 0 terminator; here's a simplistic example of how it might work:

std::ostream& operator<<( std::ostream& s, char *p )
{
  while (*p)
    s.put( *p++ );
  return s;
}

The real operator definition will be a bit more complex, but that's the basic idea.

If you want to print out just the first character of greeting, you must explicitly index or dereference it:

cout << greeting[0] << endl;

or

cout << *greeting << endl;
John Bode
  • 113,266
  • 18
  • 112
  • 190
2

greeting decays to a pointer itself. But if it sounds complicated, you can look at it as a pointer to understand what cout does.

cout method prints characters starting from greeting[0] until \0.

Community
  • 1
  • 1
Ali Seyedi
  • 1,718
  • 1
  • 19
  • 24
1

If you want to see the address value write

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << (void*)greeting << endl;
     // ^^^^^^^ 

The std::ostream& std::operator<<(std::ostream&, T type); provides specializations for the const char*, const char[] and char types.

πάντα ῥεῖ
  • 85,314
  • 13
  • 111
  • 183
0

yes greeting here is a pointer to first element in the array so if you do something like that : cout << *greeting; output will be H. but in reality when you pass it to cout object it's smart enough to know that greeting is not just a pointer but it's more it's a string according to the internal implementation of operator overloading in handling . so it's not a problem ,it's just cout can understand it.