0

I was experimenting with char array and then I tried to run this program:

#include <iostream>

using namespace std ;

int main ( )
{
    char *str = "Hello!" ;

    cout << &str[0] << endl ;
    cout << &str[1] << endl ;
    cout << &str[2] << endl ;
    cout << &str[3] << endl ;
    cout << &str[4] << endl ;

    return 0 ;
}

And I keep getting these outputs:

Hello!
ello!
llo!
lo!
o!

What exactly is happening here? I was expecting hex values.

101010
  • 41,839
  • 11
  • 94
  • 168
Parthib Biswas
  • 471
  • 1
  • 7
  • 17

2 Answers2

5

When you take the address of an array element, you get a pointer into the array.

In c++, like c, a character array (or pointer to character) is interpreted as a string, so the characters are printed out as a string.

If you want addresses, just add a cast to (void *).

#include <iostream>

using namespace std ;

int main ( )
{
    const char *str = "Hello!" ;

    cout << (void*) &str[0] << endl ;
    cout << (void*) &str[1] << endl ;
    cout << (void*) &str[2] << endl ;
    cout << (void*) &str[3] << endl ;
    cout << (void*) &str[4] << endl ;

    return 0 ;
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329
3

A char * is assumed to be a C-style string. You need to cast to void * to get the pointer value.

(And you're missing a const - string literals are immutable.)

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64