C/String Reverse function in C
Expert: Joydeep Bhattacharya - 9/29/2006
QuestionHi,
I am a beginner in C. I am trying to write a functin in C to reverse a string in place.This is the code I wrote
char *strrev(char *s,int n)
{
int i=0;
while (i<n/2)
{
*(s+n) = *(s+i); //uses the null character as the temporary storage.
*(s+i) = *(s + n - i -1);
*(s+n-i-1) = *(s+n);
i++;
}
}
I hope this should work..but when I try to debug in MSVC++ , it crashes inside the while loop..Can you please explain whats going on..
any other ways to reverse a string would be great..as I said, I am a beginner and I would definitely try to implement any other logics which would give me a good practice...
Thanks in advance ... uday
AnswerHi udaynag
This is I guess what you are looking for
char* strrev(char *s)
{
int i, j;
char *t;
strcpy(t,s);
for(i = 0 , j = strlen(s) - 1 ; j >= 0 ; i++, j--)
*(s + i) = *(t + j);
return s;
}
For more basic C functions you can refer to
http://www.scodz.com
regards
Joydeep Bhattacharya