"Reversing Reversing String" is a very vague description of a problem that allows you to use many completely different solutions.
Please note that a “smart” solution should avoid excessive line breaks. Any solution starting with strlen is not really reasonable. It is recursive for the sake of recursion and nothing more. If someone resorts to an extra pass over the line, then a recursive solution is no longer required at all. In other words, any solution starting with strlen is not really satisfactory.
So, let's look for a more reasonable single-pass recursive solution. And you almost got it already.
Your code has already taught you that the reverse character sequence is obtained at the reverse recursion stage. This is where you posted your printf . Thus, a “simple” approach would be to take these inverse characters, and instead of printf , just write them back to the original line, starting at the beginning of the line. A naive attempt to do this might look like this
void reversestring_impl(char* s, char **dst) { if (*s != '\0') { reversestring_impl(s + 1, dst); *(*dst)++ = *s; } } void reversestring5(char* s) { char *dst = s; reversestring_impl(s, &dst); }
Note that this implementation uses the optional dst parameter, which carries the destination for writing the next output character. This destination remains unchanged in the forward recursion pass and increments when writing output characters on the recursion return path.
However, the above code will not work properly, since we work "in place", that is, using the same line as the input and output at the same time. The beginning of the line will be overwritten prematurely. This will erase the character information that will be needed in the subsequent stages of the return. To work around this problem, each nested recursion level must save its current character locally before the recursive call and use the saved copy after the recursive call
void reversestring_impl(char* s, char **dst) { if (*s != '\0') { char c = *s; reversestring_impl(s + 1, dst); *(*dst)++ = c; } } void reversestring5(char* s) { char *dst = s; reversestring_impl(s, &dst); } int main() { char str[] = "123456789"; reversestring5(str); printf("%s\n", str); }
The above works as intended.