I have a simple question.
Why is it necessary to consider the terminating null in an
array of chars (or simply a string) and not in an array of integers. So when i want a string to hold 20 characters i need to declare char string[21];. When i want to declare an array of integers holding 5 digits then int digits[5]; is enough. What is the reason for this?
I have a simple question. Why is it necessary to consider the terminating null
Share
You don’t have to terminate a
chararray withNULLif you don’t want to, but when using them to represent a string, then you need to do it because C uses null-terminated strings to represent its strings. When you use functions that operate on strings (likestrlenfor string-length or usingprintfto output a string), then those functions will read through the data until aNULLis encountered. If one isn’t present, then you would likely run into buffer overflow or similar access violation/segmentation fault problems.In short: that’s how C represents string data.