C/reverse a string
Expert: Narendra - 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
AnswerMay be the string you are sending is not having 'n' places!
And in the end of your function, you are not returning the string back to the place where it is called!
I made small changes and the code is working. Here I post it for you:
#include <stdio.h>
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++;
}
*(s+n) = '\0';
return s;
}
main()
{
char *str = malloc(10);
bzero(str, 10);
sprintf(str, "abcde");
printf("%s\n", strrev(str, 5));
}