Error using this recursive program? - C ++

I participate in programming in the first C ++ class, and recently we were given a task to implement a recursive program that finds the first occurrence of a given substring in a given string.

For instance:

int StringIndex("Mississippi", "sip"); // this would return 6

The hint we give is to use a recursive helper function that takes an index as a parameter.

Here is what I have done so far:

int index_of(string s, string t)
{
    int index = 0;

    if (s[index] == NULL)
        return -1;
    else if (starts_with(s, t, ++index))
    {
        return index;
    }
    return index_of(s, t);
}

bool starts_with(string s, string t, int index)
{
    if (t[index] != s[index] || s[index] == NULL)
        return false;
    return starts_with(s, t, ++index);
}

I get an error and I don’t understand why. So could someone help me understand why I am getting this error? And help me sharpen in the right direction, how to fix it?

+3
source share
5 answers

: , , . , ( ).

, . index_of (s, t) s t . , , , .

start_with. false, .

+4
int index_of(string s, string t)
{
    ...

    // Your are calling yourself without modifying the
    // input parameters.  If you get here once, you'll
    // never break out.
    return index_of(s, t);
}

s t, .

+6

:

s[index] == NULL

, ++ std:: string NULL - - size(). , , . :

bool starts_with( const string & s, const & string t, int index)
{
   ...
}

, , , , starts_with() . , index_of() .

+2

A) "starts_with" true. , index_of .
B) index_of , .

Basically, problem 2 above leads to an infinite loop. You constantly check the same information and do not have the opportunity to exit this cycle.

+1
source

If you forgive the way to point out an error that some might find too cute, consider the difference between:

See this answer

and

If you do not understand this answer

+1
source

All Articles