Is it necessary to supply the null character when declaring an character's array?

arrays, c, string

Solution

If you are going to use C-string functions, like strlen, - then answer is YES. Your string should be null-terminated. If you introduce your custom functions to deal with string - you can store it however you like.

It's important to mention, that if you create an array using string constant, it reserves space for null-character automatically. E.g. output for the following code:

char s[] = "hello";
printf("%d", sizeof(s) / sizeof(char));

is

6

which is 5 for 'h, 'e', 'l', 'l', 'o' and 1 for '\0'.

Problem

A string constant in C is stored as a character array, while creating such an array element by element, is it necessary to supply the null character. I need to store a string constant, say, `S[number]= "hello\n"`. A string constant is stored as a character array in C, further, such a string is terminated by a null character `'\0'`. While storing the phrase in an array, do I need to account for the null character and allocate an additional space or do I just need to mention the number of characters that I need to store?

Original source

Related problems