In many code samples, people usually use \'\\0\'
after creating a new char array like this:
string s = \"JustAString\";
char* array = new char[
Why are strings in C++ usually terminated with
'\0'
?
Note that C++ Strings and C strings are not the same.
In C++ string refers to std::string which is a template class and provides a lot of intuitive functions to handle the string.
Note that C++ std::string are not \0
terminated, but the class provides functions to fetch the underlying string data as \0
terminated c-style string.
In C a string is collection of characters. This collection usually ends with a \0
.
Unless a special character like \0
is used there would be no way of knowing when a string ends.
It is also aptly known as the string null terminator.
Ofcourse, there could be other ways of bookkeeping to track the length of the string, but using a special character has two straight advantages:
Note that \0
is needed because most of Standard C library functions operate on strings assuming they are \0
terminated.
For example:
While using printf()
if you have an string which is not \0
terminated then printf()
keeps writing characters to stdout
until a \0
is encountered, in short it might even print garbage.
Why should we use
'\0'
here?
There are two scenarios when you do not need to \0
terminate a string:
\0
to strings. In your case you already have the second scenario working for you.
array[s.size()] = '\0';
The above code statement is redundant in your example.
For your example using strncpy()
makes it useless. strncpy()
copies s.size()
characters to your array
, Note that it appends a null termination if there is any space left after copying the strings. Since array
is of size s.size() + 1
a \0
is automagically added.