Does std :: string :: c_str () always return a null-terminated string?

Possible duplicate:
string c_str () vs. data ()

I use strncpy(dest, src_string, 32) to convert std::string to char[32] so that my C ++ classes work with deprecated C code. But c_str() std :: string c_str() always return a null-terminated string?

+8
c ++ string
source share
3 answers

Does std :: string c_str () always return a null-terminated string?

Yes.

This is the specification:

Returns: a pointer p such that p + i == &operator[](i) for each i in [0,size()] .

Note that the range specified for i is closed, so size() is a valid index, referring to the character that has passed after the end of the line.

operator[] specified like this:

Returns: *(begin() + pos) if pos < size() , otherwise a reference to an object of type T with value charT()

In the case of std::string , which is an alias for std::basic_string<char> , so that charT is char , the constructed char value has a value of 0; therefore, the character array pointed to by the result of std::string::c_str() ends with zero.

+20
source share

c_str returns the string "C". And C strings always end with a null character. This is standard C.

Zero trailing lines.

+11
source share

According to this , the answer is yes.

+1
source share

All Articles