Address of each character std :: string

I tried to print the address of each character std::string . But I donโ€™t understand what is happening inside with std::string , which leads to this conclusion, and for the array it gives the address, as I expected. Can someone explain what is happening?

 #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; } 

Conclusion:

 Hello ello llo lo o ************** 0x7fff5fbff950 0x7fff5fbff954 0x7fff5fbff958 0x7fff5fbff95c 0x7fff5fbff960 
+6
source share
2 answers

When a std::ostream tries to print a char* , it takes a C-style string.

Before printing, put it before void* , and you get what you expect:

 cout << (void*) &str[i] << endl; 
+13
source

or you can use old printf

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

Source: https://habr.com/ru/post/897447/


All Articles