I was curious about how C handles array initialization. I have the following code in my program:
UChar match[] = {0xdf, 'a', 'b', '\0'};
Basically, this is initializing a UTF-16 string. UChar in this case is is 16 bits.
My question is: I need the trailing NULL byte at the end of the string, but it is necessary to include it in the initialization or will C automatically include that for ALL array initializations?
Yes, you need to add a terminating '\0' (not NULL, by the way) youself - C only does that for string literals, not for any array.
For example -
char* str = "12345";
Will be an array with 6 chars, the sixth one being '\0'.
Same goes for -
char str[] = "12345";
It will have 6 items.
BUT -
char str[] = { '1', '2', '3', '4', '5' };
Will have exactly 5 items, without a terminating '\0'.
(in your initialization in the question you already have a '\0', so you need nothing else).
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