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
)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With