0

I am trying to reverse the string with return value as reversed string and input arguments as input string. Here is my code:

char* reverseString(char* string)
{
    static int i = 0;
    static char *revStr = new char[strlen(string)+1];
    if (*string)
    {
        reverseString(string + 1);
         revStr[i++] = *string;
    }
    return revStr;
}
int main(void)
{
    char* str = "Test it";
    cout << reverseString(str) << endl;;
}

output:

ti tseT═²²²²
Press any key to continue . . .

I tried this in visual studio 2013.I was expecting output to be:

ti tseT Press any key to continue . . .

But i am not getting a correct output, there are some unwanted characters getting added after "tseT". Can anyone suggest me on this? I don't want to change the function argument and return syntax.

Mat
  • 202,337
  • 40
  • 393
  • 406
A. Gupta
  • 77
  • 2
  • 9

1 Answers1

0

You need to take care of the final '\0'.

Try adding an else statement:

if (*string)
{
     revStr[i++] = *string;
    reverseString(string + 1);
}
else
    revStr[i] = '\0';
Susmit Agrawal
  • 3,649
  • 2
  • 13
  • 29