c++stringnullterminator

Why is a null terminator necessary?


I've been teaching myself c++ for the last couple days to prepare for my freshman year as a CS major. I'm on C-style strings right now, and wondering what the point of a null terminator is.

I understand that it's necessary, but I guess I just don't fundamentally understand why a string wouldn't just end on its last char.


Solution

  • I just don't fundamentally understand why a string wouldn't just end on its last char.

    There are several ways of knowing where is the "last char":

    1. Store the number of characters in the string separately from the string's characters,
    2. Put a marker that indicates the last char of the string, or
    3. Store the pointer to the last char of the string separately from the string's characters.

    C choose the second route; other languages (Pascal, etc.) choose the first route. Some implementations of C++ std::string choose the third route* .


    * Even std::string implementations that use the first or the third approach null-terminate their buffers for compatibility with the C portions of the library. This is necessary to ensure that c_str() returns a valid C string.