.data() was added in C++17. Before that, you can use &str[0].
Note that if the std::string is const, .data() will return const char * instead, like .c_str().
The pointer becomes invalid if the string is destroyed or reallocates memory.
The pointer points to a null-terminated string, and the terminator doesn't count against str.size(). You're not allowed to assign a non-null character to the terminator.
Best Answer
If you just want to pass a
std::string
to a function that needsconst char *
, you can use.c_str()
:And if you need a non-const
char *
, call.data()
:.data()
was added in C++17. Before that, you can use&str[0]
.Note that if the
std::string
isconst
,.data()
will returnconst char *
instead, like.c_str()
.The pointer becomes invalid if the string is destroyed or reallocates memory.
The pointer points to a null-terminated string, and the terminator doesn't count against
str.size()
. You're not allowed to assign a non-null character to the terminator.