You are here:

C/reverse a string

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
May 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));
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

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