Quick Tip: Recursively Reverse a Null Terminated String In-place Using C

Posted July 17, 2009 @ 9:46pm by Phil

A friend of mine recently had an interview where one of the questions he was asked was to reverse a string using recursion and the least amount of memory possible. Here is my solution which reverses the string in-place:

void str_reverse (char* start, int len)
{
   if (len <= 1) return;

   char* end = start + len - 1;

   // Swap start and end chars
   char t = *start;
   *start = *end;
   *end = t;

   str_reverse(start + 1, len - 2);
}

Download Source: str_reverse.c

Tags: C/C++, Interview Questions, Quick Tip