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?
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};
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.
\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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With