1

According to the text at http://www.cplusplus.com/reference/string/string/, string library in C++ is a class, not just a " mere sequences of characters in a memory array". I wrote this code to find out more:

string s = "abcd";

cout << &s << endl; // This gives an address
cout << s[0] << endl; // This gives 'a'
cout << &s[0] << endl; // This gives "abcd"

I have some questions: 1. Is string library in C++ still an array of sequence characters? 2. How can I get the address of each character in string? (As in the code, I can retrieve each character, but cannot get its address using & operator)

4

3 回答 3

5

Much (most) of this really isn't about the string class itself.

std::string does store its contents as a contiguous array of characters.

&s[0] will yield the address of the beginning of that array -- but std::ostream has an overload of operator<< that takes a pointer to char, and prints it as a string.

If you want to see the addresses of the individual characters in a string, you need to take their addresses and then cast each address to pointer to void. std::iostream also has an overload of operator<< that takes a pointer to void, and that overload prints out the address instead of a string that (it assumes) is at that address.

Edit: demo code:

#include <iostream>
#include <string>

int main(){
    std::string x("this is a string");

    std::cout << &x[0] << "\n";
    std::cout << (void *)&x[0] << '\n';
    return 0;
}

Result:

this is a string
00481DE0
于 2012-05-01T02:34:45.967 回答
0

std::string stores the string as essentially a vector of characters, see basic_string

于 2012-05-01T02:33:57.870 回答
-1

From Stroutrup's book, chapter 20 on strings, page 579 (2000 edition)

From C, C++ inherited the notion of strings as zero terminated arrays of char..... In C, the name of the array is same as the address of the first character. That's why you get the whole string printed when you pass &s[0] as it same as passing s itself.

于 2012-05-01T04:07:37.540 回答