I’ve always had a question about null-terminated strings in C++/C. For example, if you have a character array like so:
char a[10];
And then you wanted to read in characters like so:
for(int i = 0; i < 10; i++)
{
cin >> a[i];
}
And lets in input the following word: questioner
as the input.
Now my question is what happens to the ‘\0’? If I were to reverse the string, and make it print out
renoitseuq
Where does the null-terminating character go? I thought that good programming practice was to always leave one extra character for the zero-terminating character. But in this example, everything was printed correctly, so why care about the null-terminating character? Just curious. Thanks for your thoughts!
There are cases where you’re given a null-terminator, and cases where you have to ask for one yourself.
is a null-terminated C-style string. It actually has 4 characters – the 3 + the null terminator.
Your string isn’t null-terminated. In fact, treating it as a null-terminated string leads to undefined behavior. If you were to
cout <<it, you’d be attempting to read beyond the memory you’re allowed to access, because the runtime will keep looking for a null-terminator and spit out characters until it reaches one. In your case, you were lucky there was one right at the end, but that’s not a guarantee.char a[10];is just like any other array – un-initialized values, 10 characters – not 11 just because it’s achararray. You wouldn’t expectint b[10]to contain 10 values for you to play with and an extra0at the end just because, would you?Well, reading that back, I don’t see why you’d expect that from a C-string as well – it’s not all intuitive.