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?
&myString[0]is a object of typestd::string
No it isn't. myString[0] is a reference to the first character of the string; &myString[0] is a pointer to that character. The operator precedence is such that it means &(myString[0]) and not (&mystring)[0].
Beware that, accessed this way, there's no guarantee that the string will be zero-terminated; so if you use this in a C-style function that expects a zero-terminated string, then you'll be relying on undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With