C Program to Reverse a String Using Pointers

Pointers hold the address of the variable. So for reversing the string we need to find the ending address of the string. After finding the last address of the string we need to copy the value it holds to the reverse string rev. In order to do so we increment and decrement the pointer rptr and sptr respectively. After this step we need to again copy the rev to our original string s.

  1. //C program to reverse a string using pointers
  2. #include <stdio.h>
  3. int main()
  4. {
  5. char s[100];
  6. char rev[100];
  7. char *sptr = s; //pointer sptr stores the base address of the s
  8. char *rptr = rev; //pointer rptr stores the base address of the reverse
  9. int i = -1;
  10. printf("\n\nEnter a string: ");
  11. scanf("%s", s);
  12. // storing the ending address of s in sptr
  13. while(*sptr)
  14. {
  15. sptr++;
  16. i++;
  17. }
  18. // storing the string s in rev in reverse order
  19. while(i >= 0)
  20. {
  21. sptr--;
  22. *rptr = *sptr;
  23. rptr++;
  24. i--;
  25. }
  26. *rptr = '\0';
  27. rptr = rev;
  28. while(*rptr)
  29. {
  30. *sptr = *rptr;
  31. sptr++;
  32. rptr++;
  33. }
  34. printf("\n\nReverse of the string is: %s ", s);
  35. return 0;
  36. }

Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]

Join Our Facebook Group

Share this example

Download Android App

download android app

Popular C Examples


Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube