You are here:

C/reverse string program in c

Advertisement


Question
hi, i saw your code about reversing a string in c.
Would it be possible if you could send me a copy of it with comments as i am new to programming and c and am currently doing a project that seems very similar.
I would also be very greatful if you could give me a quick example of how a function works.

Thanks alot

martin

Answer
Here is the code, that I posted in my previous answer.
And if you are a C programmer, you will understand that.
And it is very simple program and easy to understand.
If you have any difficulty in understanding this, please let me know.


#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.