Jurriaan Buitenweg Jurriaan Buitenweg - 3 months ago 8
C++ Question

How to get the memory adresses from a string?

I have a very basic question but i just cant get my head around it.
I wondered how i can retrieve the memory adresses of each charachter in a string.

For example:

string str("Test");
cout << size(str) << endl;


I know this returns this 4 because this string is 4 bytes but how can i output the memory adresses of each byte on the screen?

I did try this

string s = "abcd";
string::iterator pos;

for (pos = s.begin(); pos != s.end(); ++pos) {
cout << &pos << endl;
}

cin.get();
return 0;


But this is the output :

00AFFB8C
00AFFB8C
00AFFB8C
00AFFB8C


But doesnt it needs to be someting like :

00AFFB8C
00AFFB8D
00AFFB8E
00AFFB8F


So does anyone have an idea what I'm doing wrong here?

Answer

Just change your loop to:

for (pos = s.begin(); pos != s.end(); ++pos) {
      cout << static_cast<void*>( &*pos ) << endl;
}

static_cast is necessary because &*pos has type char * which would be printed by std::ostream not the way you want.