Reverse a string in C using pointers

Reverse a string in C using pointers with code example and explanation.

Input: I am coding string reverse!

Output: !esrever gnirts gnidoc ma I

Logic to Reverse a string in C:

Store the string into a buffer. Take two pointers e.g. start pointer and end pointer.

Set the start pointer to the first location of the buffer and end pointer to the end location of the buffer.

Swap the values of both the pointers. Move the start pointer one step forward by incrementing it and move the end pointer one step back by decrementing it.

Keep doing the same up to the middle of the string resides in the buffer.

C Code to reverse string:

The function void reverse_string(char* str) takes the input string in a pointer and process the reversing of the string in place in the buffer itself.

Read the comments given for each required code statements.

/*------------ Reverse a string in C using pointers --------
*/

#include <stdio.h> 
#include <string.h> 

/*function - Reverse a string in c using pointers

It recieves a string in a buffer pointed by a pointer
and reverse it in the buffer itself. 
*/
void reverse_string(char* str)
{
	int len; // for string lenght
	int index;// for pointing elements in the buffer
	char *start_ptr, *end_ptr, temp;

	// Get length of the string using strlen() library function
	len = strlen(str);

	// Set the start_ptr and end_ptr 
	// to start location and end location of the buffer respectively.
	
	start_ptr = str;// base address of the buffer
	end_ptr = str+len-1;// now points to end location	

	// Swap the char from start and end 
	// index using start_ptr and end_ptr 
	for (index = 0; index < len / 2; index++) {

		// swap values of the both pointers 
		temp = *end_ptr;
		*end_ptr = *start_ptr;
		*start_ptr = temp;

		// After swapping the elments ,increase the
		//start pointer by 1 postion to point to the next
		//element and decrease the end pointer by 1 for next swapping
		
		start_ptr++; 
		end_ptr--;
	}
}

// Test string reversal function 
int main()
{	
	//Set some buffer size up to which you can enter the string
	char str[50];
	printf("Enter the string to be reversed:");	
	fgets(str, sizeof(str), stdin);  // read entered string
	
	reverse_string(str);

	// Check the result
	printf("%s", str);

	return 0;
}

Related Posts