Search code examples
ccharacter-arrays

Initializing C char array using curly braces, is it okay to omit null byte '\0'?


So I read that:

char pattern[] = "ould";

is basically the easier way of writing:

char pattern[] = { 'o', 'u', 'l', 'd', '\0' };

I understand that the null character \0 marks the end of a string, but what if I write it like:

char pattern[] = { 'o', 'u', 'l', 'd'}; (without the \0)

It still compiles.

Where would pattern without the \0 cause problems, because it seems to be compile without warnings (-Wall)


Solution

  • If you leave off the terminating zero, you no longer have a null terminated string, just an array of char, so passing it to any function that expects a string would be an error. E.g. strlen, as the source parameter to strcpy, as a ... parameter to printf with a %s format specifier, etc.