0
#include <iostream>

#include <string.h>

using namespace std;

int main()

{

    char x[100]="hello";

    int s=strlen(x);

    cout<<&(x[0]);

}

If I compile and run it,

the output is hello

Why isn't the output the address of the charecter 'h' ?

2 Answers2

10

Because the operator << is overloaded for const char* to print the zero-terminated C-string pointed to by the const char*.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
1

Pointers do not keep the information whether they point to a single object or the first object of an array. Also take into account that array names in expressions are converted to pointers to their first elements. So if you have for example a pointer of type const char * like this

const char *p = "Hello";

then it is naturally to expect that this statement

std::cout << p << std::endl;

will output string literal "Hello".

If you want to output the address of the first element of the string literal you have to use another overloaded operator << for pointers of type void *

std::cout << ( const void * )p << std::endl;

So there is a dilemma how to process pointers of type char * and it was resolved in favor to consider such pointers as pointers to first elements of character strings and consequently to output the whole string.

Shoe
  • 74,840
  • 36
  • 166
  • 272
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • May I ask why you keep rolling back perfectly valid edits that improve the formatting of your own answer? – Shoe Feb 24 '15 at 14:31
  • @Jefffrey Yes, you may ask.:) I did not roll back edits. It seems that we were editing simultaneously and when I was saving my edits your edits had been discarded.:) – Vlad from Moscow Feb 24 '15 at 14:33