Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 797
user225312 Avatar asked Nov 28 '22 10:11

user225312


2 Answers

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.

like image 78
CB Bailey Avatar answered Dec 21 '22 01:12

CB Bailey


What's wrong with this behaviour? It is perfectly valid to have a char array without a '\0' on the end. Its just an array. The only reason the '\0' exists is to delimit the string. If you know what the length is, you don't need it!

Char arrays aren't special from other arrays. The only thing you need the '\0' for are the standard string functions.

like image 42
alternative Avatar answered Dec 21 '22 00:12

alternative