Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a null character at end of a string object in C++?

Tags:

c++

string

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!

like image 548
user1050165 Avatar asked Jul 22 '13 05:07

user1050165


People also ask

Does a string have a null character at the end?

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.

What is the end character of a string in C?

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 .

Why do we have null character at the end of a string in C?

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".

Do all C strings end in null?

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.


2 Answers

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.

like image 82
Tony Delroy Avatar answered Oct 17 '22 18:10

Tony Delroy


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.

like image 43
Arno Duvenhage Avatar answered Oct 17 '22 17:10

Arno Duvenhage