I have to implement a function that determines the length of a string without using library functions. My function looks like this:
int getLength(char strg[]) {
int length = 0;
while(strg[length] != '\0') {
length++;
}
return length;
}
With the inputs
char test1[7] = "BlaBlaB"
as well as
char test2[8] = {'B','l','a','B','l','a','B','l'}
the function returns the values 11 and 12, which are of course wrong.
However, with
char test1[8] = "BlaBlaB"
or
char test2[9] = {'B','l','a','B','l','a','B','l'}
the function returns the correct results.
So to sum it up, only for the cases where the array is assigned as many elements as it is defined to be allowed to hold, and only when the number of elements is 7 or 8, this bug occurs. Also, it doesn't matter if I assign the value with String notation ("ab..."
) or if I assign it in array notation ({'a','b','.','.','.'}
).
Does anyone have an explanation for this weird behaviour?