简体   繁体   中英

Reverse array in C recursively

Here's a part of my code, where I am trying to reverse a string recursively:

    char reverse[10];
    gets(reverse);
    reverseString(reverse, (strlen(reverse) - 1));
    void reverseString(char ar[], int n)
    {
        if (n == 0)
        {
            return;
        }
        else
        {
            int temp = ar[n];
            ar[n] = *(ar);
            *(ar) = temp;
            reverseString((ar + 1), (n - 1));
        }
    }

When I enter the string "hello" it changes the string to "ohell". I need it to reverse the string totally to "olleh". Can someone help?

Since you swap the first and last element of the array, you should recursively call the function with the remaining n-2 elements (instead of n-1 ),

void reverseString(char ar[], int n)
{
    if (n <= 0)
    {
        return;
    }
    else
    {
        int temp = ar[n];
        ar[n] = *(ar);
        *(ar) = temp;
        reverseString((ar + 1), (n - 2));
    }
}

(I have assumed that reverseString and reverseAr in your code are actually the same functions, perhaps some copy-paste error.)

# include <stdio.h>

/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if(*str)
   {
       reverse(str+1);
       printf("%c", *str);
   }
}

/* Driver program to test above function */
int main()
{
   char a[] = "Geeks for Geeks";
   reverse(a);
   getchar();
   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