We all know there is a null character automatically attached to the end of a C-string...How about C++ string object? Is there also a null character at the end of it?
Thank you so much!
All character strings are terminated with a null character. The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0.
Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character , which is simply the character with the value 0. (The null character has no relation except in name to the null pointer .
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello".
C strings are null-terminated. That is, they are terminated by the null character, NUL . They are not terminated by the null pointer NULL , which is a completely different kind of value with a completely different purpose.
In C++03, a std::string was not required to be stored in a NUL-terminated buffer, but if you called c_str()
it would return a pointer to a NUL-terminated buffer. That buffer could legally be created and/or terminated inside the c_str()
call.
In C++11, all std::string
instances are terminated, so data()
also addresses a NUL-terminated buffer, and even s[s.size()]
has a well-defined meaning returning a reference to the terminating NUL.
std::string
is very much a std::vector
: it has a length attribute and is not zero terminated in C++03; in C++11 'std::string' does seems to be terminated, but I find it easier to think of 'std::string' as a 'std::vector' of characters and not just a terminated buffer.
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