When/Why is '\0' necessary to mark end of an (char) array?

Strict picture Strict · Nov 26, 2016 · Viewed 23.9k times · Source

So I just read an example of how to create an array of characters which represent a string.

The null-character \0 is put at the end of the array to mark the end of the array. Is this necessary?

If I created a char array:

char line[100]; 

and put the word:

"hello\n"

in it, the chars would be placed at the first six indexes line[0] - line[6], so the rest of the array would be filled with null characters anyway?

This books says, that it is a convention that, for example the string constant "hello\n" is put in a character array and terminated with \0.

Maybe I don't understand this topic to its full extent and would be glad for enlightenment.

Answer

AnT picture AnT · Nov 26, 2016

The \0 character does not mark the "end of the array". The \0 character marks the end of the string stored in a char array, if (and only if) that char array is intended to store a string.

A char array is just a char array. It stores independent integer values (char is just a small integer type). A char array does not have to end in \0. \0 has no special meaning in a char array. It is just a zero value.

But sometimes char arrays are used to store strings. A string is a sequence of characters terminated by \0. So, if you want to use your char array as a string you have to terminate your string with a \0.

So, the answer to the question about \0 being "necessary" depends on what you are storing in your char array. If you are storing a string, then you will have to terminate it with a \0. If you are storing something that is not a string, then \0 has no special meaning at all.