0

I don't know if I just don't understand arrays or what, but I've been looking for the problem in this code for the last couple of hours. When I run it, I get an infinite loop of returns.

Here's the code:

#include <stdio.h>
#include <string.h>

void reverse(char string2Reverse[80], int start, int end);

int main(int argc, char *argv[])
{
    char string[80];

    int cntr;
    for(cntr = 0; cntr < 80; cntr++)
        string[cntr] = '\0';

    int start = 0, end;

    while((scanf("s", string)) != EOF)
    {
    end = 0;
    printf("%s ", string);

    while(string[end] != '\0')
        end++;

    end--;
    reverse(string, start, end);
    end++;
    printf("%s\n\n", string);

    for(cntr = 0; cntr < end; cntr++)
        string[cntr] = '\0';
    }
}

void reverse(char string2Reverse[80], int start, int end)
{
    if(string2Reverse[start] != string2Reverse[end] && start != end)
    {
    char temp = string2Reverse[start];
    string2Reverse[start] = string2Reverse[end];
    string2Reverse[end] = temp;
    reverse(string2Reverse, start + 1, end - 1);
    }
}

Any help would be awesome! I can't seem to find my problem.

1
  • 1
    It is often helpful to only provide as much code as needed to exhibit the problem. Here replacing input with constants would be a good idea as it makes automatic verification harder. Commented Oct 17, 2012 at 19:15

3 Answers 3

2

If end-start is not even, you'll infinite loop because start will != end ever .. also i dont' know if you actually want to be comparing the string2Reverse[start] != string2Reverse[end] like that, that means if there is a place in the string where there is an 'a' and in the balanced position on the other side of a string there is also an 'a', it'll terminate. Try this:

void reverse(char string2Reverse[80], int start, int end)
{
    if(start < end)
    {
    char temp = string2Reverse[start];
    string2Reverse[start] = string2Reverse[end];
    string2Reverse[end] = temp;
    reverse(string2Reverse, start + 1, end - 1);
    }
}

And as everyone else pointed out here, you need "%s" instead of "s" in your scanf, the reason why you're looping right now is because end starts off as -1 (since it was a zero len string), so obviously start is increasing and end is decreasing, so your termination condition never met.

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

Comments

1

scanf's format to read strings is %s, it seems you're missing the percent sign.

Comments

1

while((scanf("s", string)) != EOF) should be while((scanf("%s", &string)) != EOF) dont forget % and &.

Comments

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.