Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.c_str() is const? [duplicate]

Tags:

c++

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?

like image 849
jmasterx Avatar asked Jun 06 '12 14:06

jmasterx


People also ask

Why does c_str return const?

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.

What is string c_str ()?

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.

What does c_str return?

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.

How long is c_str valid?

The const char* returned from c_str() is only valid until the next non-const call to the std::string object.


1 Answers

You can use &str[0] or &*str.begin() as long as:

  • you preallocate explicitly all the space needed for the function with resize();
  • the function does not try to exceed the preallocated buffer size (you should pass str.size() as the argument for the buffer size);
  • when the function returns, you explicitly trim the string at the first \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.

like image 169
Matteo Italia Avatar answered Sep 25 '22 01:09

Matteo Italia