Recursive Call Crashing program

Description:

I'm trying to write a recursive function that takes a null terminated char array, and then counts the number of characters in it and returns the length. The array that is sent to the length function has a fixed size of 10.

Problem:
The program keeps crashing. I debugged it and the problem is coming from the line of code return length(str); Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int length(char str[])
{
    int currentIndex;
    int count;
  
  if(str[currentIndex] == '\0')
       return 0;
  else
      currentIndex++;
      count++;
      length(str); 

return count;
                   
    
}
Last edited on
A few things:

You aren't initializing "currentIndex" or "count", so these values are just associated with the value of whatever bit data was in their part of the memory last. What you may want to do is to do something like this instead:

1
2
3
4
5
6
7
8
int length (char *str) {
    if (*str == '\0') // If the value that the string is pointing to is NULL
        return 0;     // Return length as zero
    
    // Otherwise, return the length of the string, one past the current
    // character, with one added to it.
    return (length(str+1) + 1);
}
Last edited on
Aw man, I was so close! I tried that code^^ exactly, but I was just missing that second +1. Anyways thanks, and yeah I usually do initialize, I'm not sure how I left that out this time. Thanks you!
Topic archived. No new replies allowed.