3

I have written code to reverse a string in c... it works fine but I can't return the reversed string in the main() function.

#include<stdio.h>

main()
{
  char a[17]="abcdefg";
  reverse(a);
  printf("\n");
  system("PAUSE");
}
int reverse(char *a)
{
   if(*a!='\0')
   {   
     reverse(a+1);
   }
   printf("%c",*a);
}         

it prints the reversed string but I want the reversed string in main(). How can I do this?

5
  • Is this a homework assignment? Commented Oct 3, 2012 at 11:15
  • nopes i am studying recursion Commented Oct 3, 2012 at 11:18
  • The int reverse() function should at least return an int. Commented Oct 3, 2012 at 11:20
  • 1
    You have to swap characters in the string (an in-place reverse) rather than printing them. A recursive solution is inefficient but can be done fairly easily. Commented Oct 3, 2012 at 16:01
  • Instead of focusing on mostly useless knowledge, such as recursion, you should focus on useful knowledge, such as C99/C11 and how to write function prototypes in modern C. Your code contains several bugs and they are not related to recursion, but to basic C programming. Commented Feb 10, 2017 at 14:45

12 Answers 12

6

Following is one way to reverse string using recursion!

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

void rev_str_recursive(char arr[], size_t iStart, size_t iLast)
{
    if( iStart < iLast )
    {
        //swap
        char temp = arr[iStart];
        arr[iStart] = arr[iLast];
        arr[iLast] = temp;

        rev_str_recursive(arr, ++iStart, --iLast);  
    }
}

void main()
{
    char cArray[] = {"A quick brown fox jumps over a lazy dog"};

    rev_str_recursive(cArray, 0, strlen(cArray)-1);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Because of the -1 in the original invocation of the function, this fails horribly when the string is empty (so strlen(cArray) is 0, so the value passed as iLast is the maximum value of size_t). You can simplify the interface by calling it as rev_str_recursive(cArray, strlen(cArray)) and arranging the recursive call as rev_str_recursive(arr+1, iLast-2); only when iLast > 2. Of course, since it is tail recursive, the code can be optimized to a loop without recursion.
Thanks for the feedback, I concur with you, if the string is empty this will fail!
5

You need to modify the string, i.e. the input buffer to reverse(), instead of just printing it.

Doing this recursively seems a bit obnoxious, but should of course be possible.

Basically, I guess the printing becomes an assignment, something like this:

  1. Base: The reversal of an empty string is the empty string.
  2. Step: The reversal of a string begins by swapping the first and last characters, then recursing over the remainder of the string.

Comments

2

Here is another way to reverse a string using recursion:

void reverseString(char* dest, char *src, int len) {
    if (src == NULL || len == 0)
        return;

    reverseString(dest, src + 1, len - 1);
    strncat_s(dest, len + 1, src, 1);
}

You can call like that:

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

#define STRING "Let's try this one."
#define SIZE 20

void main() {

    char* src = (char*)malloc(SIZE);
    char* dest = (char*)malloc(SIZE);

    strcpy_s(dest, SIZE, "");
    strcpy_s(src, SIZE, STRING);

    reverseString(dest, src, strlen(src));
    /* Do anything with dest. */
    // printf("%s\n", dest);

    free(src);
    free(dest);
}

Comments

0

This code is not executable :( You define int reverse but reverse function doesnt return any value

instead use this (using void):

#include<stdio.h>

main()
{
  char a[17]="abcdefg";
  reverse(a);
  printf("\n");
  system("PAUSE");
}
void reverse(char *a)
{
   if(*a!='\0')
   {   
     reverse(a+1);
   }
   printf("%c",*a);
}        

1 Comment

How does this change the value of a?
0
#include <iostream>
using namespace std;

reverse( char *str)
{
    if (*str!='\0')
    {
       reverse(str+1);
       cout<<*str;
    }
//cout<<*str   when i am just printing here then why this is printing after one space ??
}

int main()
{   
    string a ;  
    cin>>a;   
    reverse(&a[0]); 
    return 0;
}

1 Comment

This is not an answer so much as you copying and pasting code in. Also, please use code indentation when answering with code snippets.
0

a little change in Emre Can Kucukoglu's answer . . . we can eliminate strncat_s

void revstr_rec(char *sstr, char *dstr, int len)
{
    int i = 0;
    if((! *sstr) || (! len) )
        return;

    revstr_rec(sstr + 1, dstr, len - 1);
    dstr[len - 1] = *sstr;

    return;
}

int main()
{
    char *sstr = NULL;
    char *dstr = NULL;

    sstr = malloc(16);
    if(! sstr)  {
        printf("no memory . . .\n");
        return 0;
    }
    strcpy(sstr, "hello world !");
    printf("sstr: %s\n", sstr);

    dstr = malloc(16);
    if(! dstr)  {
        printf("no memory . . .\n");
        return 0;
    }

    revstr_rec(sstr, dstr, strlen(sstr));
    printf("dstr(recursive): %s\n", dstr);

    free(sstr);
    free(dstr);

    return 0;
}

Comments

0
#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX], *rev;
scanf("%s", str);
rev = reverse(str); 
printf("The reversed string is : %s\n", rev);
return 0;
}
char *reverse(char ch[])
   {
    static char r[MAX];
    static int i=0;
    if(*ch == '\0') return "";
    else 
   {
    reverse(ch+1);
    r[i++]=*ch;
   }
    return r;
   }

Comments

0

A simple way with left and right index

void main()
{
    char* str = (char*)malloc(strlen("somestring")+1);
    strcpy(str, "somestring");
    int leftIndex = 0;
    int rightIndex = strlen(str) - 1;
    
    printf("%s\n", ReverseString(str, leftIndex, rightIndex));
    free(str);
}

char* ReverseString(char* str, int leftIndex, int rightIndex)
{
    if (leftIndex == rightIndex || leftIndex == (rightIndex +1)) {
        return str;
    }

    // flip letters
    char leftLetter = *(str + leftIndex);
    char rightLetter = *(str + rightIndex);
    *(str + leftIndex) = rightLetter;
    *(str + rightIndex) = leftLetter;

    return ReverseString(str, leftIndex+1, rightIndex -1);
}

Comments

-1

use sprintf it will print your reversed string into buffer.

#include<stdio.h>

char *b;

main()
{
  char a[17]="abcdefg";
  char buffer[17];
  buffer[0]= '\0';
  b = buffer;
  reverse(a);
  printf("%s\n",buffer);
}
int reverse(char *a)
{
   if(*a!='\0')
   {   
     reverse(a+1);
     sprintf(b,"%c",*a);
     b++;
   }

}

1 Comment

There is a semicolon missing after char buffer[17]. Also: buffer is not an lvalue, so buffer++; is not possible.
-1
void palindromo(char *s)
{
    if(s[0] != '\0'){
        palindromo(s+1);
        printf("%c", s[0]);
    }
}

This is a small recursive function who print the string inverted.

Comments

-1
#include<stdio.h>
#include<string.h>
void rev(char *);

int main()
{
    char s[]="Hello";
    printf("\n%s",s);
    rev(s);
    printf("\n%s",s);
    return 0;
}

void rev(char *s)
{
    static int i=0;
    static int j=0;
    if(j==0)                   //since static variable can be intitialized 
    {                          //only with a constant literal,to store 
        j=strlen(s)-1;         //length-1 in 1st function call, we can use 
    }                          //this trick.(condition satisfied only in 1st 
                               //function call)
    if(i<j)
    {
        char temp;
        temp=s[i];
        s[i]=s[j];             //Analogous to for(i=0,j=l-1;i<j;i++,j--)
        s[j]=temp;             //                { //swap code }
        i++;
        j--;
        rev(s);           
    }
}

3 Comments

Using static variables to record state is not using recursion correctly. You may as well have written a loop and avoided a possible race condition.
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
@ Nic3500 Thank you for the suggestion.
-3
#include<stdio.h>
void reverse(char *a);
main()
{
  char a[17]="abcdefg";
  reverse(a);
  printf("\n");
  system("PAUSE");
}
void reverse(char *a)
{
   if(*a!='\0')
   {   
     reverse(a+1);
   }
   printf("%c",*a);
}  

4 Comments

Did you do anything but copy the code from the question?
He added the forward declaration of reverse(char* a) didn't he?
@Edd: Two thoughts: 1. The question was about reversing the string in such a way that it could be accessed from the calling function. 2. When you post an answer that is only code, a big far warning comes up saying "maybe you should explain what this code block is doing".
@BillLynch I'm not disagreeing with any of that (and I voted/edited accordingly) I was just trying to answer you question as to whether anything had changed.

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.