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.
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":
C choose the second route; other languages (Pascal, etc.) choose the first route. Some implementations of C++ std::string
choose the third route* .
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.
In C and C++, c-strings are stored in a character array. To allow strings of different lengths, these arrays are often allocated much larger than the actual strings they are to contain. For example, a programmer may allocate a char[256]
array, which can hold a string with a length anywhere between 0 characters and 255. But the computer has to be able to know exactly how long the string actually is, so it must end with a null character. Otherwise, it would be neccessary for the character array length to be exactly the same as the string (an impractical solution, as allocating and copying memory uses a lot of resources).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With