I usually find some functions with char*
as its parameter.But I heard that std::string
is more recommended in C++. How can I use a std::string
object with functions taking char*
s as parameters? Till now I have known the c_str()
, but it doesn't work when the content of string should be modified.
For that purpose, you use std::string::data()
. Returns a pointer to the internal data. Be careful not to free this memory or anything like that as this memory is managed by the string object.
You can use the address of the first element after C++11
like this:
void some_c_function(char* s, int n);
// ...
std::string s = "some text";
some_c_function(&s[0], s.size());
Before C++11
there was no guarantee that the internal string was stored in a contiguous buffer or that it would be null terminated. In those cases making a copy of the string was the only safe option.
After C++17
(the current standard) you can use this:
some_c_function(s.data(), s.size());
In C++17
a non-const return value of std::string::data() was added in addition to the const version.
Since C++17 std::string::data()
returns a pointer to the underlying char
array that does allow to modify the contents of the string. However, as usual with strings, you may not write beyond its end. From cppreference:
Modifying the past-the-end null terminator stored at data()+size() to any value other than CharT() has undefined behavior.
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