I'm new to programming and very new to C++, and I recently came across strings.
Why do we need a null terminator at the end of a character list?
I've read answers like since we might not use all the spaces of an array therefore we need the null terminator for the program to know where the string ends e.g. char[100] = "John"
but why can't the program just loop through the array to check how many spaces are filled and hence decide the length?
And if only four characters are filled in the array for the word "John", what are the others spaces filled with?
The other characters in the array
char john[100] = "John"would be filled with zeros, which are all null-terminators. In general, when you initialize an array and don't provide enough elements to fill it up, the remaining elements are default-initialized:Also see cppreference on Array initialization. To find the length of such a string, we just loop through the characters until we find
0and exit.The motivation behind null-terminating strings in C++ is to ensure compatibility with C-libraries, which use null-terminated strings. Also see What's the rationale for null terminated strings?
Containers like
std::stringdon't require the string to be null-terminated and can even store a string containing null-characters. This is because they store the size of the string separately. However, the characters of astd::stringare often null-terminated anyways so thatstd::string::c_str()doesn't require a modification of the underlying array.C++-only libraries will rarely -if ever- pass C-strings between functions.