简体   繁体   中英

string reverse using recursion

can someone please tell me what is the problem in my code? it is showing some strange output.

#include<stdio.h>
#include<string.h>
void reverse(char string[])
{
    char b[200];
    int t;
    t = strlen(string);
    if (t==1)
        printf("%c",string[0]);
    else
    {
        printf("%c",string[t-1]);
        for (int i=0;i<t-1;i++)
            b[i]=string[i];
        reverse(b);
    }
}
int main()
{
    char a[200];
    scanf("%s",&a);
    reverse(a);
    return 0;
}

If you had tried to use a debugger, you would see that t is going mad on second iteration. This is because after you have copied string into b you forgot to insert \\0 symbol at the end (position with index t-1 ). This causes t become literally anything on the next iteration because of strlen() needs a null-terminating string and it results in an undefined behaviour as mentioned in docs :

The behavior is undefined if str is not a pointer to a null-terminated byte string

So a quick fix is as folows:

...
for (int i=0;i<t-1;i++)
{
    b[i]=string[i];
}
b[t-1] = '\0';
reverse(b);
...

And as already mentioned in comments by @LPs : change scanf("%s",&a); to scanf("%199s",a); (199 because we need to leave a space for '\\0' at the end, thanks to @RoadRunner for noticing that)

Note: take a look at strncpy_s (if you use C11) and use it instead of that for loop:

printf("%c",string[t-1]);
strncpy_s(b, 200, string, t-1);       // 200 because char b[200]
reverse(b);

or strncpy :

printf("%c",string[t-1]);
strncpy(b, string, t-1); 
b[t-1] = '\0';
reverse(b);

Still another approach is not to copy:

else
{
    string[t-1] = '\0';    // you don't need array 'b' at all
    reverse(string);
}

And the simpliest way is just to use a loop:

for (int i = strlen(string) - 1; i >= 0; --i)
{
    printf("%c", string[i]);
}

The easiest way to reverse a string using recursion is like this:

 // C++ program to reverse a string using recursion # include <stdio.h> # include<string> using namespace std; string in=""; /* Function to print reverse of the passed string */ void reverse(char *str) { if (*str) { reverse(str+1); in=in+*str; /* If you want to save the reversed string */ printf("%c", *str); /*If you just want to print the reversed string */ } } /* Driver program to test above function */ int main() { char a[] = "Reversing a string using recursion"; reverse(a); printf("\\n%s\\n",in.c_str()); return 0; } /* output : noisrucer gnisu gnirts a gnisreveR */

Explanation:

Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way, when pointer reaches '\\0', all functions accumulated in stack print char at passed location (str) and return one by one.

Time Complexity: O(n)

You mix up two approaches, ie recursive and loop, in one function. Further, for me it remains unclear whether you want to change the input string to a reverse order, or if you just want to print it out in reverse order. Anyway, see a solution that provides loop bases reverse printing and recursion based reverse printing; hope it helps in understanding the steps the code such goes through:

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

void reverse_loop(char string[]) {
    long i = strlen(string) - 1;
    while (i >= 0)
        printf("%c",string[i--]);
}

void reverse_recursive (char string[]) {
    if (string[0] != '\0') {
        reverse_recursive(&string[1]);
        printf("%c", string[0]);
    }
}

int main()
{
    char a[200] = { "some test string" };
    reverse_recursive(a);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM