I am writing a function to check length of a char array in c. It takes another parameter, which sets the limit for \0
check.
int string_length(char* string, int maximum_length) {
int i = 0;
while(string[i] != '\0' && i < maximum_length) {
i++;
}
return i;
}
In this answer, it is mentioned that a char array must be null terminated, if it is created using {}
syntax. I call the above function with not terminated char array & the result is 10(9 letters + 1).
char not_terminated_string[] = {'m', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g' };
int length = string_length(not_terminated_string, 100);
// length is 10
I am not able to understand why is it this way.