Ishvar Patel Ishvar Patel - 4 years ago 122
C Question

Which is better way to initialize array of characters using string literal?

I'm newbie in

C
language. I'm trying to understanding concept of array in C. I have a confusion about array initialize.

Which is better way to initialize array of characters using string literal?

char arr[3] = "xyz";


or

char arr[] = "xyz";


Thanks in advance.

rsp rsp
Answer Source

Which is better way to initialize array of characters using string literal?

2nd way better to initialize array of characters.

C standard(c11 - 6.7.8 : paragraph 14) says:

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

Whenever initializes an array of characters using string literal, do not specify the bound of a string intitialized with a string literal because the compiler will automatically allocate sufficient space for entire string literal,including the terminating null character.

char arr[3] = "xyz";

In this way, size of arr is 3, but size of the string literal is 4. string defines one charater more(terminating '\0') than the array can hold.

char arr[] = "xyz";

In this way, does not specify the bound of a character array in the array initialize. If the array bound is omitted, the compiler allocates sufficient size to store entire string literal, including null character.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download