Vanilo
Vanilo

Reputation: 23

Why does the address of the first element in 'std::string' print out as the whole string?

Let's say that a string has a value of "Test string". I tried printing out &string[0] and what I got is the same thing but what I expected was a 'T'. When I tried printing out &string[1] I got "est string". Can someone explain why does it work this way?

Upvotes: 1

Views: 876

Answers (1)

Rene
Rene

Reputation: 2474

string[0] returns the first character from the string.
&string[0] is the address of this first character, of type char*, so when you pass that to std::cout or printf() (with %s), it will print the whole string up to the terminating \0 character.

The same applies of course to string[1] etc.

Edit:
But, as Daniel correctly pointed out, before C++ 11 this behaviour was not guaranteed. You should use std::string::c_str() in this case.

Upvotes: 6

Related Questions