OiO.lk Blog C# Why do we need a null terminator only in strings in C?
C#

Why do we need a null terminator only in strings in C?


I’m taking CS50X. I’m on week 2 now. my question is: why do we need a null character ‘\0’ in strings (aka null terminated char arrays) to mark its end, while we don’t need it in normal char arrays or a non-string data type array such as an int array , like while printing both arrays (the null terminated char array and the int array for example) what does mark the end of the second array?

I tried to demonstrate how strings are implemented for myself with some code:

this code worked printing "hi!" in the terminal

this also worked printing the three scores

Why in the first code did we need an additional place in the array for the null character? Couldn’t we have used i < 3 instead as we did in the second code? A character array, like any other array, has a specific length, so what changed when we decided to treat string as a character array?



You need to sign in to view this answers

Exit mobile version