Address of each character of std::string

╄→гoц情女王★ 提交于 2019-12-04 23:09:37

问题


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

回答1:


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;



回答2:


or you may use the old printf

printf("\n%x",&s[i]);


来源:https://stackoverflow.com/questions/7440746/address-of-each-character-of-stdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!