Why does a char array have to end with a null character? Is there any reason that I have to add the null character to to every char array ?
It seems that they get treated the same way.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In C, if you have a pointer to an array, then there is not way to determine the length of that array. As @AProgrammer points out, the designers could have left it at that and forced the programmer to keep track of the length of all character arrays. However, that would have made text processing in C even harder than it already is.
Therefore the language designers settled on a convention that would allow string length to be inferred by the presence of a null character indicating the end of the string.
For example, consider
strcpy:There is no way in C to determine the length of the array that the pointers
destinationandsourcepoint to. So, without the presence of a sentinel value to indicate the end of the string, the only other solution would have been to pass extra parameters indicating the length of thesourcestring.Of course, in light of modern security considerations, string processing functions that receive buffer length parameters have been introduced. But the computing landscape looked very different at the time that the null-terminated string was invented.