0

I understand what pointer is but for characters and strings it is quite confused to me. I have I piece of code as below:

#include <iostream>

using namespace std;

int main ()
{
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   cout << "Address of 'H' is: "; // line 1
   cout << &greeting << endl;     // line 2
   cout << "Address of 'e' is: "; // line 3
   cout << &(greeting[1]) << endl;// line 4
   cout << "Address of 'l' is: "; // line 5 
   cout << &(greeting[2]) << endl;// line 6

   return 0;
}

and the output is:

Address of 'H' is: 0x7fff30f13600
Address of 'e' is: ello
Address of 'l' is: llo

Can someone help me to explain why line 4 and line 6 does not produce address?

Lundin
  • 195,001
  • 40
  • 254
  • 396
Thanhpv
  • 64
  • 1
  • 8
  • 4
    Because cout << char* is specialised ... you want to cast it to a void* if you want the address – UKMonkey Oct 21 '16 at 09:20
  • Why do you think `"Address of 'H' is: "` would print the string but `&(greeting[1])` wouldn't? Think about what types these are. – Simple Oct 21 '16 at 09:27
  • try `cout << &greeting << &greeting[0]` and see. And [don't use `endl` unless you really want its behavior](http://stackoverflow.com/q/213907/995714), use `'\n'` instead – phuclv Oct 21 '16 at 09:41

2 Answers2

2

It has nothing to do with the address-of operator & in this case.

The operator

std::ostream& operator<<(std::ostream&, const char*);

is a specialized overload to output NUL terminated C-strings.

If you want to print the address, use a cast to void*:

cout << (void*)&greeting[1] << endl;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

Because strings are actually a charachter arrays.

when printing cout << greetings

it is the equivalent of cout << &(greetings[0])

which is starting printing chars from the address of the first char until you hit a null terminator.

Aus
  • 1,183
  • 11
  • 27