std :: string的每个字符的地址

Mah*_*esh 6 c++ arrays string memory-address

我试图打印每个角色的地址std::string.但是我不知道内部发生了什么,std::string这导致了这个输出,而对于数组,它给出了我预期的地址.有人可以解释一下发生了什么吗?

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Hello
ello
llo
lo
o
**************
0x7fff5fbff950
0x7fff5fbff954
0x7fff5fbff958
0x7fff5fbff95c
0x7fff5fbff960
Run Code Online (Sandbox Code Playgroud)

man*_*nge 14

std::ostream试图打印char*它时,它假定它是一个C风格的字符串.

void*在打印之前将其投射到您将获得您期望的内容:

cout << (void*) &str[i] << endl;
Run Code Online (Sandbox Code Playgroud)