C array initialization

I was wondering how C handles array initialization. My program has the following code:

UChar match[] = {0xdf, 'a', 'b', '\0'}; 

Basically, this initializes the UTF-16 string. UChar in this case is 16 bits.

My question is: do I need a final NULL byte at the end of the line, but must it be included in the initialization or will C automatically turn on to initialize the ALL array?

+4
source share
3 answers

Yes, you need to add the trailing '\ 0' (not NULL, by the way) yourself - C does this only for string literals , and not for any array.

For instance -

 char* str = "12345"; 

There will be an array with 6 characters, the sixth is '\ 0'.

The same for -

 char str[] = "12345"; 

He will have 6 elements.

BUT -

 char str[] = { '1', '2', '3', '4', '5' }; 

Will have exactly 5 elements without a trailing '\ 0'.

(in your initialization in the question, you already have "\ 0", so you don't need anything else).

+11
source

If you ever want to manipulate a char array as a string, you'll need a trailing character.

+1
source

You can do this if you do not want to explicitly specify \0 for the string. Suppose you know that your string contains 5 letters, and then create an array like this

 char str[6]={'h','e','l','l','o'}; 

My point is that even if you are half initializing the array, the rest of the values ​​are padded with 0s . For example,

 int arr[5]={1,2,3}; 

now if you do

 printf("%d",a[3]); or printf("%d",a[4]); 

both will be 0 .

0
source

Source: https://habr.com/ru/post/1332510/


All Articles