[TuT] Recursive function to reverse an array of characters

Juni0r_r00t

Newbie
Joined
Aug 23, 2009
Messages
3
Reaction score
0
Hi,

This code causes the reversal of an array of characters using a recursive function.


javascript:void(0);
Code:
#include <stdio.h>

void inv(char *string)
{
if(*string)
{
inv(string+1);
putchar(*string);
}
}
int main()
{
inv("kleber");
return 0;
}

Explaining:




int main ()
(
inv ( "linux"); / / when you call the function passing a string inv
/ / she attaches to the str pointer memory address
/ / the first character of string ..... in this case 'l'
return 0;
)

void inv (char * str)
(
if (* str) / / if the contents of the pointer "* str" is different from 0 ..........
(
inv (str +1); / / sum 1 in memory location
/ / the program calls the function again
/ / address of the next character as a parameter
putchar (* str) / / when he leaves if thereby ending
/ / function it is returning the characters
/ / pending and so is q it shows the opposite ...
)
)
 
Nice little tut, I'm sure it could be useful for someone. I suggest you put the comments in the actual code block instead of just redoing it all below.

_Austin
 
Back
Top