1
\$\begingroup\$

I just finished this exercise where i should reverse a string with a recursive function. First of all, i created a separate function called swap to swap the chars, should i write it as function pointer?. After i call the function recursively untill i reach the base case, the if check if the variable "lenght" is 1 or 0, bacause the string can be even or odd. Any tips to improve this code? i don't know it's seems pretty ugly.

#include <stdio.h>
#include <string.h>

void swap(char arr[], int pos, int pos_2){
  char sent = arr[pos_2];
  arr[pos_2] = arr[pos];
  arr[pos] = sent;

}

void recursive_mirror(char arr[], int lenght){


  if(lenght == 0 || lenght == 1){
    return;
  }

  swap(arr, 0, lenght - 1);
  lenght--;
  recursive_mirror(arr + 1, lenght - 1);

}



int main(void) {

  char arr[] = "mirror";
  recursive_mirror(arr,strlen(arr));
  printf("%s\n", arr);
  return 0;
}
\$\endgroup\$
1
  • \$\begingroup\$ Unfortunately, you've misspelt "length". I'm guessing that English isn't your first language, so this is understandable (and would easily be corrected), so I'm not writing an answer with only this comment in it! \$\endgroup\$ Mar 6, 2018 at 10:51

1 Answer 1

3
\$\begingroup\$
  • swap would be is a nice general purpose swap routine. Notice that in your code you always call it with pos equal to 0. You should either drop this redundant parameter, or make swap even more general purpose by not assuming the semantics of the parameters, e.g.:

    void swap(char * ptr1, char * prt2) {
        char ch = *ptr1;
        *ptr1 = * ptr2;
        *ptr2 = ch;
    }
    

    In this version, ptr1 and ptr2 do not have to belong to the same array.

  • recursive_mirror decrements length twice, and the first decrement has a side effect. The (non-existent) purpose of this side effect takes an effort to understand. A direct

      swap(arr, 0, length - 1);
      recursive_mirror(arr + 1, length - 2);
    

    seems more readable).

  • The base case test can be if (length < 2).

    Nitpick: your base case tests fails miserably on a negative length. However, from the very beginning we know that length shall not be negative, so declaring it as an unsigned seems more prudent. At least the intention is documented.

\$\endgroup\$
1
  • \$\begingroup\$ In void swap how can i swap the 2 char if i don't have the position of the second char? I mean the first is 0 so it's ok but for the second? how can char * ptr2 can point to arr[lenght - 2] ? \$\endgroup\$
    – Robert
    Mar 7, 2018 at 5:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.