5

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?

1
  • Depends if the array is fixed. Commented Dec 17, 2010 at 14:44

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

1

If you ever want to manipulate the char array as a string then you'll need the terminating character.

Comments

0

You can do this if you dont want to put a \0 explicitly for a string Suppose you know that your string contains 5 letters then create an array like this

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

My point is that even if you half-initialize an array the rest of the values are padded with 0s. So 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.