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?
Does std::string's c_str() method always return a null-terminated string?
Yes.
It's specification is:
Returns: A pointer
p
such thatp + i == &operator[](i)
for eachi
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)
ifpos < size()
, otherwise a reference to an object of typeT
with valuecharT()
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.
c_str returns a "C string". And C strings are always terminated by a null character. This is C standard.
Null terminating strings.
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