Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

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

I use strncpy(dest, src_string, 32) to convert std::string to char[32] to make my C++ classes work with legacy C code. But does std::string's c_str() method always return a null-terminated string?

like image 700
ezpresso Avatar asked Oct 02 '12 20:10

ezpresso


2 Answers

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

Yes.

It's specification is:

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 that size() is a valid index, referring to the character past the end of the string.

operator[] is specified thus:

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, a value-constructed char has the value zero; therefore the character array pointed to by the result of std::string::c_str() is zero-terminated.

like image 150
Mike Seymour Avatar answered Oct 24 '22 01:10

Mike Seymour


c_str returns a "C string". And C strings are always terminated by a null character. This is C standard.

Null terminating strings.

like image 27
Lews Therin Avatar answered Oct 24 '22 01:10

Lews Therin