Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't numeric arrays end with a '\0' or null character?

Tags:

arrays

c

Why don't the numeric arrays end with a null character?

For example,

char name[] = {'V', 'I', 'J', 'A', 'Y', '\0'}; 

But in case of numeric arrays there is no sign of null character at the end...

For example,

int marks[] = {20, 22, 23}; 

What is the reason behind that?

like image 775
Vijay Chauhan Avatar asked Oct 12 '13 08:10

Vijay Chauhan


People also ask

Do all arrays end with null character?

char name[] = {'V', 'I', 'J', 'A', 'Y', '\0'}; But in case of numeric arrays there is no sign of null character at the end... For example, int marks[] = {20, 22, 23};

Why a char array must end with a null character?

If your char array represents a string then if you omit the null terminator every function working with C strings will not return the correct value or will behave differently than expected.

Why do we have a null character 0 or NUL at the end of a string?

\0 is used to mark end of character string in C. Most C std library functions requires the string to be terminated this way in order to work. Since C does not know how long is your string you must mark the end with a \0 so it knows it has reached the end of your string.

Does integer array terminate with null character?

Integer arrays are not C-style strings, and there is no null-terminator values in them (otherwise the array would end at the first zero).


1 Answers

The question asked contains a hidden assumption, that all char arrays do end with a null character. This is in fact not always the case: this char array does not end with \0:

char no_zero[] = { 'f', 'o', 'o' }; 

The char arrays that must end with the null character are those meant for use as strings, which indeed require termination.

In your example, the char array only ends with a null character because you made it so. The single place where the compiler will insert the null character for you is when declaring a char array from a string literal, such as:

char name[] = "VIJAY"; 

In that case, the null character is inserted automatically to make the resulting array a valid C string. No such requirement exists for arrays of other numeric types, nor can they be initialized from a string literal. In other words, appending a zero to a numeric array would serve no purpose whatsoever, because there is no code out there that uses the zero to look for the array end, since zero is a perfectly valid number.

Arrays of pointers are sometimes terminated with a NULL pointer, which makes sense because a NULL pointer cannot be confused with a valid pointer. The argv array of strings, received by main(), is an example of such an array.

like image 79
user4815162342 Avatar answered Oct 11 '22 12:10

user4815162342