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

后端 未结 5 1073
心在旅途
心在旅途 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:11

    In C, we represent string with an array of char (or w_char), and use special character to signal the end of the string. As opposed to Pascal, which stores the length of the string in the index 0 of the array (thus the string has a hard limit on the number of characters), there is theoretically no limit on the number of characters that a string (represented as array of characters) can have in C.

    The special character is expected to be NUL in all the functions from the default library in C, and also other libraries. If you want to use the library functions that relies on the exact length of the string, you must terminate the string with NUL. You can totally define your own terminating character, but you must understand that library functions involving string (as array of characters) may not work as you expect and it will cause all sorts of errors.

    In the snippet of code given, there is a need to explicitly set the terminating character to NUL, since you don't know if there are trash data in the array allocated. It is also a good practice, since in large code, you may not see the initialization of the array of characters.

提交回复
热议问题