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

后端 未结 5 1060
心在旅途
心在旅途 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条回答
  •  萌比男神i
    2020-11-27 19:01

    strncpy(array, s.c_str(), s.size());
    array[s.size()] = '\0';
    

    Why should we use '\0' here?

    You shouldn't, that second line is waste of space. strncpy already adds a null termination if you know how to use it. The code can be rewritten as:

    strncpy(array, s.c_str(), s.size()+1);
    

    strncpy is sort of a weird function, it assumes that the first parameter is an array of the size of the third parameter. So it only copies null termination if there is any space left after copying the strings.

    You could also have used memcpy() in this case, it will be slightly more efficient, though perhaps makes the code less intuitive to read.

提交回复
热议问题