I have to write a function that recursively returns a string from the end. The following 3 functions are available for us:
#include <stdio.h>
#include <stdlib.h>
int length(char* s) {
int n = 0;
while (*s != '\0') {
n++;
s++;
}
return n;
}
void copy(char* s, int n, char* t) {
int i = 0;
while (i < n) {
t[i] = s[i];
i++;
}
}
char* putBack(char* s, char c) {
const int n = length(s);
char* r = malloc(sizeof(char) * (n + 2));
copy(s, n, r);
r[n] = c;
r[n + 1] = '\0';
return r;
}
My implemented recursive method is:
char* reverseRec(char* s) {
char* pointer = s;
char* string;
if (*pointer == '\0') {
return pointer--;
}
else{
string = reverseRec(pointer + 1);
string = putBack(string, *pointer);
return string;
}
}
For example, if I have "call" as input, then "llac" is the output. So, the method should work. My question now is how can I clean up the reserved space of putBack()
(there is a malloc) with free()
after each call?
Thanks for helping! :)