Why are strings in C++ usually terminated with '\0'?

后端 未结 5 1053
心在旅途
心在旅途 2020-11-27 18:43

In many code samples, people usually use \'\\0\' after creating a new char array like this:

string s = \"JustAString\";
char* array = new char[         


        
5条回答
  •  北海茫月
    2020-11-27 19:00

    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:

    • It is more intuitive and
    • There are no additional overheads

    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 \0terminated 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:

    • In any usage if you are explicitly bookkeeping length of the string and
    • If you are using some standard library api will implicitly add a \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 arrayis of size s.size() + 1 a \0 is automagically added.

提交回复
热议问题