I usually understand recursions pretty well, but because I’m new to C functions like strcpy and pointers I couldn’t figure out how this recursion reverses a string:
char *reverse(char *string)
{
if (strlen(string) <= 1)
return string;
else
{
char temp = *string;
strcpy(string, reverse(string+1));
*(string+strlen(string)) = temp;
return string;
}
}
The strcpy part seems a little bit complicated to me, and also what’s the purpose of this line:
*(string+strlen(string)) = temp;?
I realize that after flipping the string you need to add the character that was at the beginning to the end of the string, but I’m not sure I understand the logic behind this code.
This code is extremely inefficient but what it does is:
string+1is a pointer to the second character in the string).*(string+strlen(string)) = temp;).The
*(string+strlen(string)) = temp;is equivalent tostring[strlen(string)] = temp;if that is easier to understand.I will not recommend using this code at all, since it is extremely inefficient — it copies the entire string (and measures its length twice) in every iteration, not to mention waste stack space.
A much better implementation would be: