std::string.c_str()
returns a (const char *) value. I Googled and found that I can do the following:
std::string myString = "Hello World";
char *buf = &myString[0];
How is this possible? &myString[0]
is an object of type std::string
, so how can this work?
There are
const
and non-const
overloads ofstd::string::operator[]( size_type pos )
, and the non-const version returns achar&
, so you can do things likeNote that, since
s[0]
returnschar&
, then&s[0]
is the address of elements[0]
. You can assign that address to achar*
. It is up to you not to misuse this pointer.It has to do with operator precedence. The
[]
operator has higher precedence than the address-of operator&
, so the address-of operator works on the character reference returned by the stringsoperator[]
function.The std::string methods
c_str()
andoperator[]
are two diferent methods, which return two different types.The method c_str() does indeed return a
const char*
.However, the method operator[] returns instead a reference to a char. When you take the address of it, you get the address of a char.
The
std::string
type has anoperator[]
that allows indexing each one of the characters in the string. The expressionmyString[0]
is a (modifiable) reference to the first character of the string. If you take the address of that you will get a pointer to the first character in the array.You are wrong.
&myString[0]
is not of typestd::string
, it is of typechar *
.The
[]
operator has higher precedence andoperator[]
returns a reference tochar
, and its address (the&
operator) is of typechar *
.The operator
[]
(std::string::char& operator[] (size_t pos)) overloaded returns a reference to the character at the index. You are taking the address of such character reference which is fine.So,
myString[0]
return type is notstd::string
butchar&
.There is no reason to do it. You can directly do -