You are here:

C/String Reverse function in C

Advertisement


Question
Hi,

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

Answer
Hi 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

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joydeep Bhattacharya

Expertise

Ability to solve C and Data Structure problems and puzzles with simple and easy to understand logic.

Experience

C, C++, Java, Data Structure, PHP, Web Designing

Organizations
http://www.scodz.com Designation: webmaster

Publications
http://www.scodz.com

Education/Credentials
Master of Computer Applications

Past/Present Clients
http://analysingc.50webs.com http://www.funforu.com

©2012 About.com, a part of The New York Times Company. All rights reserved.