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

char *Change(char *str,int start,int end)
  {
  if(start==end || start>end){
    return str;
  }

  else{
    char temp=str[start];
    str[start]=str[end];
    str[end]=temp;
    return(Change(str,start++,end--));
  }
  return str;
}


char *Reverse(char *str)
{
   int length=strlen(str);
  return(Change(str,0,length-1));
}

int main()
{
   printf("%s\n",Reverse("program"));
   return 0;
}

I am trying to write a recursive function to reverse a string,but it comes the linking error.Please help.I had tried so many times and searched in the Internet,but it can't help. I guess the most probably place causing the problem is in function Change,but I can't solve with it.

luojiebin
  • 103
  • 2
  • 3
  • 14

2 Answers2

1

You're passing a string literal (which is a const char*) to Reverse(), since you can't modify a string literal, your program generates a segmentation fault.

You'll either need to pass a modifiable string to Reverse():

char myStr[] = "program";
printf("%s\n",Reverse(myStr));

Or you can make a copy of the input string in Reverse():

char *Reverse(const char *str)
{
   int length=strlen(str);
   char* temp = malloc(length);
   strcpy(temp, str);
   return(Change(temp,0,length-1));
}

In that case, you'll need to free the string returned by Reverse():

char* reverseStr = Reverse("program");
printf("%s\n", reverseStr );
free(reverseStr);

Also in change(), start++ end end-- will return the value before they are incremented, you need to use either ++start or simply start+1 since you won't use those variables anymore:

return(Change(str,start+1,end-1));
zakinster
  • 10,508
  • 1
  • 41
  • 52
0

Simple explanation: You can't modify a string literal. One more thing is that the statement

return(Change(temp,0,length-1));  

will cause compilation error because neither temp is defined in the function Reverse nor it is globally defined.

haccks
  • 104,019
  • 25
  • 176
  • 264