arraysccharc-stringsnull-terminated

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.


Solution

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

    The terminating zero is necessary if a character array contains a string. This allows to find the point where a string ends.

    As for your example that as I think looks the following way

    char line[100] = "hello\n";
    

    then for starters the string literal has 7 characters. It is a string and includes the terminating zero. This string literal has type char[7]. You can imagine it like

    char no_name[] = { 'h', 'e', 'l', 'l', 'o', '\n', '\0' };
    

    When a string literal is used to initialize a character array then all its characters are used as initializers. So relative to the example the seven characters of the string literal are used to initialize first 7 elements of the array. All other elements of the array that were not initialized by the characters of the string literal will be initialized implicitly by zeroes.

    If you want to determine how long is the string stored in a character array you can use the standard C function strlen declared in the header <string.h>. It returns the number of characters in an array before the terminating zero.

    Consider the following example

    #include <stdio.h>
    #include <string.h>
    
    int main(void) 
    {
        char line[100] = "hello\n";
        
        printf( "The size of the array is %zu"
                "\nand the length of the stored string \n%s is %zu\n",
                sizeof( line ), line, strlen( line ) );
                
        return 0;
    }
    

    Its output is

    The size of the array is 100
    and the length of the stored string 
    hello
     is 6
    

    In C you may use a string literal to initialize a character array excluding the terminating zero of the string literal. For example

    char line[6] = "hello\n";
    

    In this case you may not say that the array contains a string because the sequence of symbols stored in the array does not have the terminating zero.