Strict Strict - 14 days ago 5
C Question

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

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

You need the null character to mark the end of the string. C does not store any internal information about the length of the character array or the length of a string, and so the null character/byte \0 marks where it ends.

This is only required for strings, however – you can have any ordinary array of characters that does not represent a string.

For example, try this piece of code:

#include <stdio.h>

int main(void) {
    char string[1];
    string[0] = 'a';
    printf("%s", string);
}

Note that the character array is completely filled with data. Thus, there is no null byte to mark the end. Now, printf will keep printing until it hits a null byte – this will be somewhere past the end of the array, so you will print out a lot of junk in addition to just "a".

Now, try this:

#include <stdio.h>

int main(void) {
    char string[2];
    string[0] = 'a';
    string[1] = '\0';
    printf("%s", string);
}

It will only print "a", because the end of the string is explicitly marked.