I have a function in a library that takes in a char*
and modifies the data.
I tried to give it the c_str()
but c++ docs say it returns a const char*
.
What can I do other than newing a char array and copying it into that?
The pointer returned by c_str is declared to point to a const char to prevent modifying the internal string buffer via that pointer. The string buffer is indeed dynamically allocated, and the pointer returned by c_str is only valid while the string itself does not change.
The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object.
The function c_str() returns a const pointer to a regular C string, identical to the current string. The returned string is null-terminated. Note that since the returned pointer is of type (C/C++ Keywords) const, the character data that c_str() returns cannot be modified.
The const char* returned from c_str() is only valid until the next non-const call to the std::string object.
You can use &str[0]
or &*str.begin()
as long as:
resize()
;str.size()
as the argument for the buffer size);\0
character you find, otherwise str.size()
will return the "preallocated size" instead of the "logical" string size.Notice: this is guaranteed to work in C++11 (where strings are guaranteed to be contiguous), but not in previous revisions of the standard; still, no implementation of the standard library that I know of ever did implement std::basic_string
with noncontiguous storage.
Still, if you want to go safe, use std::vector<char>
(guaranteed to be contiguous since C++03); initialize with whatever you want (you can copy its data from a string using the constructor that takes two iterators, adding a null character in the end), resize it as you would do with std::string
and copy it back to a string stopping at the first \0
character.
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