Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Array Initialization

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?

like image 275
Scott Avatar asked Dec 17 '22 19:12

Scott


1 Answers

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).

like image 132
Hexagon Avatar answered Dec 28 '22 13:12

Hexagon