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.
- //C program to reverse a string using pointers
-
- #include <stdio.h>
- int main()
- {
- char s[100];
- char rev[100];
- char *sptr = s; //pointer sptr stores the base address of the s
- char *rptr = rev; //pointer rptr stores the base address of the reverse
-
- int i = -1;
-
- printf("\n\nEnter a string: ");
- scanf("%s", s);
-
- // storing the ending address of s in sptr
- while(*sptr)
- {
- sptr++;
- i++;
- }
-
- // storing the string s in rev in reverse order
- while(i >= 0)
- {
- sptr--;
- *rptr = *sptr;
- rptr++;
- i--;
- }
- *rptr = '\0';
- rptr = rev;
- while(*rptr)
- {
- *sptr = *rptr;
- sptr++;
- rptr++;
- }
- printf("\n\nReverse of the string is: %s ", s);
- return 0;
- }
Output

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