Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it mandatory to give '\0' for initialization of character arrays?

Please see the code:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char name[10] = {'L','e','s','s','o','n','s'}; // did not add `\0`
    char c;

    for (int i = 0; name[i] != '\0'; i++)
    {
        c = name[i];
        printf("%c", c);
    }

    return 0;
}

I did not give \0 at the end, but still it works.

My question: Is \0 added automatically in the above case?

EDIT: What happens in these cases:

  1. char name[7] = {'L','e','s','s','o','n','s'};
  2. char name[8] = {'L','e','s','s','o','n','s'};

I apologize for editing the question.

like image 755
Krishna Kanth Yenumula Avatar asked Dec 04 '22 17:12

Krishna Kanth Yenumula


1 Answers

In C, partially initialized arrays of any type are 0-initialized for the rest. So,

int foo[5] = {1, 2, 3};

will initialize foo with {1, 2, 3, 0, 0}. So, when you don't add '\0' to the end, not only will the end be '\0' (assuming the array is large enough to fit it), but all remaining elements of the array will be '\0'.

If your array isn't large enough to fit the null terminator, then it won't be added, nor should the value even matter. Reading past the end of an array is undefined behavior, which can lead to segfaults, garbage data, or worse.

like image 146
Aplet123 Avatar answered May 01 '23 15:05

Aplet123