-3

While trying to reverse a string of characters using the mentioned program, the string reverses only till half. I don't know where the problem is occuring

void reverse(char *s)
{
    char *t=s;
    while(*t)
        t++;
    t--;
    while(*s)
    {
        char temp=*t;
        *s++=*t;
        *t--=temp;
    }
}

int main()
{
    char s[100];
    gets(s);
    reverse(s);
    cout<<s;
    return 0;
}
001
  • 13,291
  • 5
  • 35
  • 66
  • 1
    [Don't use gets](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – crashmstr Sep 10 '15 at 15:17

1 Answers1

3

You store the value of t in temp, and then later assign temp back to t again!

You meant to store the value of s in temp, so that t gets the value that was in s before.


Also, you don't want to keep swapping characters all the way through the string!
If you do, you'll swap the first-character with with the last one, and then later, swap the last one with the first one again!

You want your swap-loop to be:

while(s < t)
{
    char temp=*s;
    *s++=*t;
    *t--=temp;
}

Link to IDEOne

abelenky
  • 63,815
  • 23
  • 109
  • 159