Pointers and char

I want to know how to get the address of a character from a char array.

If i do this..
1
2
3
4
    char man[10] = "Lock";
    char *charpointer = &man[0];
    cout << charpointer << endl;
}

..I get as a result "Lock" instead of the address like in integers

If i do this..
cout << *charpointer << endl;
..I get "L".

But, if i do this..
cout << *charpointer + 1 << endl;
..I get "77" instead of "o". Is this the address or no?
Last edited on
..I get as a result "Lock" instead of the address like in integers


The << operator is treated special for char pointers so that strings can be printed. This allows for cout << "foo"; to print the text rather than print an address you probably don't care about... since the string literal is treated as a pointer in this case as well.

If you want to print the actual address... you will need to "trick" the << operator into thinking that this is not a char pointer, but is instead some other kind of pointer. This can easily be accomplished by casting it so some other kind of pointer... like a void pointer:

 
cout << reinterpret_cast<void*>(charpointer) << endl;



..I get "77" instead of "o". Is this the address or no?


No. That is the numerical value of the letter 'M', which is 1+'L'. It is printed as a number instead of a character because once you perform the addition it is promoted to an int, and therefore the << operator no longer treats it as a char.

again... chars are special.
Thank you! Now i get it, i think. Although i don't understand exactly what reinterpret_cast<void*>(charpointer) is, but i understand what it does.
Topic archived. No new replies allowed.