Hello to everyone out there. Recently many people on different forums have been asking how to make a recursive function which reverses the string passed to it. But unlike the normal recrusive funtion which only prints out the reversed string, this implementation returns a pointer to reversed string.
Recursive String reversal returning reversed string
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* The actual recursive algo which works behind the scenes
*
* @author ~s.o.s~
* @param src_string The pointer to constant character string which is to be used for reversing
* @param dest_string The pointer to the string which will hold the reversed string
* @return a pointer to the reversed string
*/
char* _string_reverse( const char* src_string, char* dest_string )
{
if( *src_string != '\0' )
{
*dest_string-- = *src_string++ ;
_string_reverse( src_string, dest_string ) ;
}
return dest_string ;
}
/**
* Acts as a simple interface which the main function or any function can call, hides the recursive nature of algo used.
*The creation of the string to be returned occurs in this function which is then used by the recursive alg
*
* @author ~s.o.s~
* @param my_string The const string to be reversed
* @return Returns the reversed string
*/
char* string_reverse( const char* my_string )
{
int length = strlen( my_string ) ;
char* reversed = (char*) malloc( length + 1) ;
reversed[ length ] = '\0' ;
char* tmp = &( reversed[ 0 ] ) ; /// preserve the original pos for returning
reversed = &(reversed[ length - 1 ]) ;
reversed = _string_reverse( my_string, reversed ) ;
return tmp ;
}
/** The driver function which calls the core functionality
* @author ~s.o.s~
*/
int main( void )
{
const char* my_string = "Hello All !!" ;
char* reversed = string_reverse( my_string );
printf( "\n\nOriginal String: %s and Reversed String: {%s}", my_string, reversed ) ;
return 0 ;
}
bumsfeld 413 Nearly a Posting Virtuoso
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
roverphoenix 0 Newbie Poster
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
roverphoenix 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.