C program to reverse a string using pointers
Learn how to reverse a string in C using pointers with this step-by-step guide. Explore efficient string manipulation techniques, detailed explanations, and example code for mastering string reversal in C programming.
Reversing a string is a common task in programming that can be approached in various ways. In C, pointers provide a powerful tool to manipulate strings efficiently. This article will guide you through writing a C program to reverse a string using pointers.
Understanding Pointers and Strings in C
In C, a string is an array of characters ending with a null character (\0
). Pointers, which store memory addresses, allow direct manipulation of array elements, making operations like reversing a string straightforward and efficient.
Steps to Reverse a String
- Initialize pointers: Use pointers to point to the start and end of the string.
- Swap characters: Swap characters from the start and end, moving towards the center.
- Continue until pointers meet: Ensure all characters are swapped by the time the pointers meet in the middle.
Write a C program to find reverse of a string using pointers
Here is a simple C program to reverse a string using pointers:
#include <stdio.h>
#include <string.h>
// Function to reverse a string using pointers
void reverseString(char *str) {
// Pointers pointing to the start and end of the string
char *start = str;
char *end = str + strlen(str) - 1;
char temp;
// Swap characters from start and end moving towards the center
while (start < end) {
// Swap the characters
temp = *start;
*start = *end;
*end = temp;
// Move the pointers towards the center
start++;
end--;
}
}
int main() {
char str[100];
// Input a string from the user
printf("Enter a string: ");
gets(str);
// Reverse the string
reverseString(str);
// Output the reversed string
printf("Reversed string: %s", str);
return 0;
}
Output
Enter a string: ProCoding
Reversed string: gnidoCorP
Explanation
- Input Handling:
- The program reads a string from the user using
gets
.
- The program reads a string from the user using
- String Reversal Function:
- The
reverseString
function takes achar *
pointer (the string) as an argument. - Two pointers,
start
andend
, are initialized to point to the beginning and the end of the string, respectively. - A
while
loop swaps the characters at thestart
andend
pointers, then moves the pointers towards the center until they meet.
- The
- Swapping Logic:
- A temporary variable
temp
is used to facilitate the swap of characters. - The
start
pointer is incremented, and theend
pointer is decremented after each swap.
- A temporary variable
- Output:
- The main function calls
reverseString
and then prints the reversed string.
- The main function calls
Benefits of Using Pointers
- Efficiency: Direct manipulation of memory addresses can be faster than using array indices.
- Flexibility: Pointers can be easily manipulated to point to different parts of the array, providing more control.