Address of each character of std::string

2020-06-18 10:16发布

I tried to print the address of each character of std::string. But I amn't understanding what is happening internally with std::string that is resulting this output while for the array it is giving the address as I expected. Could someone please explain what is going on?

#include <iostream>
#include <string>

using namespace std;

int main(){

   string str = "Hello";
   int a[] = {1,2,3,4,5};

   for( int i=0; i<str.length(); ++i )
      cout << &str[i] << endl;

   cout << "**************" << endl;

   for( int i=0; i<5; ++i )
      cout << &a[i] << endl;

    return 0;
}

Output:

Hello
ello
llo
lo
o
**************
0x7fff5fbff950
0x7fff5fbff954
0x7fff5fbff958
0x7fff5fbff95c
0x7fff5fbff960

2条回答
叼着烟拽天下
2楼-- · 2020-06-18 11:02

When a std::ostream tries to print a char* it assumes it's a C-style string.

Cast it to a void* before printing and you will get what you expect:

cout << (void*) &str[i] << endl;
查看更多
何必那么认真
3楼-- · 2020-06-18 11:12

or you may use the old printf

printf("\n%x",&s[i]);
查看更多
登录 后发表回答