Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers.
Examples:
Input: Geeks Output: skeeG Input: GeeksForGeeks Output: skeeGroFskeeG
Approach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these two pointers.
Program:
#include <stdio.h> #include <string.h> // Function to reverse the string // using pointers void reverseString(char* str) { int l, i; char *begin_ptr, *end_ptr, ch; // Get the length of the string l = strlen(str); // Set the begin_ptr and end_ptr // initially to start of string begin_ptr = str; end_ptr = str; // Move the end_ptr to the last character for (i = 0; i < l - 1; i++) end_ptr++; // Swap the char from start and end // index using begin_ptr and end_ptr for (i = 0; i < l / 2; i++) { // swap character ch = *end_ptr; *end_ptr = *begin_ptr; *begin_ptr = ch; // update pointers positions begin_ptr++; end_ptr--; } } // Driver code int main() { // Get the string char str[100] = "GeeksForGeeks"; printf("Enter a string: %s\n", str); // Reverse the string reverseString(str); // Print the result printf("Reverse of the string: %s\n", str); return 0; } |
chevron_right
filter_none
Output:
Enter a string: GeeksForGeeks Reverse of the string: skeeGroFskeeG
Recommended Posts:
- Program to reverse an array using pointers
- C++ Program to compare two string using pointers
- The length of a string using pointers
- Different methods to reverse a string in C/C++
- Reverse a string in C/C++ using Client Server model
- C Program to Reverse Array of Strings
- Program to copy the contents of one array into another in the reverse order
- C program to print a string without any quote (singe or double) in the program
- Applications of Pointers in C/C++
- Pointers in C/C++ with Examples
- Pointers vs References in C++
- What are near, far and huge pointers?
- Smart Pointers in C++
- What are Wild Pointers? How can we avoid?
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



