In this example, we will learn to reverse a string using pointers. The best part is that we will not reverse the string and copy it onto another string, but we will reverse the original string itself.
C Program to Reverse a String Using Pointers
Let's create a file named reversestring.c and add the following source code to it.
#include <stdio.h> void main() { char str[255], *ptr1, *ptr2, temp ; int n,m; printf("Enter a string: "); scanf("%s", str); ptr1=str; n=1; while(*ptr1 !='\0') { ptr1++; n++; } ptr1--; ptr2=str; m=1; while(m<=n/2) { temp=*ptr1; *ptr1=*ptr2; *ptr2=temp; ptr1--; ptr2++;; m++; } printf("Reverse string is %s", str); }
To compile and run the above C program, you can use C Programs Compiler Online tool.
Output:
Enter a string: sourcecodeexamples Reverse string is selpmaxeedocecruos
Comments
Post a Comment