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;
}
-
\$\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\$Toby Speight– Toby Speight2018年03月06日 10:51:31 +00:00Commented Mar 6, 2018 at 10:51
1 Answer 1
swap
would be is a nice general purpose swap routine. Notice that in your code you always call it withpos
equal to0
. You should either drop this redundant parameter, or makeswap
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
andptr2
do not have to belong to the same array.recursive_mirror
decrementslength
twice, and the first decrement has a side effect. The (non-existent) purpose of this side effect takes an effort to understand. A directswap(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 thatlength
shall not be negative, so declaring it as anunsigned
seems more prudent. At least the intention is documented.
-
\$\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– Robert2018年03月07日 05:28:59 +00:00Commented Mar 7, 2018 at 5:28