Reputation: 34625
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
Upvotes: 6
Views: 9974
Reputation: 3212
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;
Upvotes: 15