Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string getting (char *) instead of (const char *)

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?

like image 736
user1365914 Avatar asked Dec 07 '25 23:12

user1365914


1 Answers

&myString[0] is a object of type std::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.

like image 112
Mike Seymour Avatar answered Dec 09 '25 15:12

Mike Seymour