0

I'm kida new to the recursion subject and i've been trying to write the "strlen" function using recurion, thats what i tried:

int strlen ( char str[], int i)
{
    if ( str[i] == 0) return i+1;
    return strlen(str,i++);
}

and i tried something very similiar

int strlen( char str[], int i)
{
    if ( str[i] == 0) return 1;
    return strlen(str,i++) + 1;
}

and in my main function

int main()
{
     char word[MAX_DIGITS];
     scanf("%s",word);
     printf("%d", strlen(word,0));
     return 0;
}

but my program would crash whenever i run it, what am I missing? (I'm using C90 btw)

4 Answers 4

4
size_t strlen (char* str) {
    if (*str == 0) {
        return 0;
    }

    return strlen (str+1) +1;
}

So :

  • strlen ("") == 0
  • strlen ("a") -> strln("") + 1 == 1
  • strlen ("he") -> strln("e") + 1) = (strln("") + 1) + 1 == 2

etc

Sign up to request clarification or add additional context in comments.

Comments

3

Your problem starts here:

i++

This is called a postfix. Just use ++i or i + 1

Postfix sends the value and just then increments the variable. It's like writing this:

return strlen(str,i);
i = i + 1;

You have to use Prefix, which increments the variable and then sends the value. A prefix (++i) will act like that:

i = i + 1;
return strlen(str,i);

Or just send the value without changing the variable:

return strlen(str, i + 1);

Which, in my opinion, is the simplest way to do that.

Comments

2
return strlen(str,i++);

You are using the wrong increment operator. i++ means the original value of i is passed as argument, and then it's incremented. That means infinite recursion.

You should try ++i instead, or better, i + 1.

1 Comment

Actually I think i+1 i clearer in this situation, but your point is valid :-)
2

If you want to keep the same prototype as strlen does. This is how i see a strlen with recursion.

size_t strlen(char *str)
{
    static int i = 0;

    if (*str != '\0')
    {
        i++;
        return ft_strlen(++str);
    }
    return i;
}

I know it's not the best way to do it. Just my implementation.

1 Comment

The correct prototype for strlen is size_t strlen(const char *s);. And don't worry too much about the best way, since recursion can never be the best way to write this function. Using recursion for this will always be a horrible idea in real-world programming.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.