#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void reversefill(char*const from,char*const to){
if(from>=to){
//Nothing to do. Odd lengths get to from==to.
//Even lengths 'swap over'.
//Pointer comparison guaranteed legit - in the same array.
return;
}
//Textbook swap.
//Could use the classic xor swap trick.
//However that will just confuse in this example.
const char temp=*from;
*from=*to;
*to=temp;
//Carry on moving our 'work' points closer together from both ends.
reversefill(from+1,to-1);
}
void reverse(char* str){
const size_t sz=strlen(str);
if(sz==0){
return;//Can't use str-1 - UB.
//Could head for the door if sz==1 but this is a training example on recursion.
//So we'll just show it works if from==to.
}
reversefill(str,str+sz-1);
}
int main() {
char*const str="Hello World!";
char*const rev=malloc(strlen(str)*sizeof(*str));//sizeof not required but good habit
strcpy(rev,str);
reverse(rev);
printf("%s\n",rev);
free(rev);//Don't listen to smart-arses who say that's unnecessary.
//Unless you really need to use the trick...
//However examples should be the cleanest possible code.
return EXIT_SUCCESS;
}
I think the requirement was in-place reversal.
The only way to do that (I think the OP realises) is to work from the ends and swap 'symmetric' positions. That is swap the first with last, second with second last, etc.
That's fine but we need to realise when we've 'met' in the middle.
That's obvious of odd length cases - the two working points meet.
For even cases we need to spot the workings 'crossing over'.
That's exactly how reversefill(,) works.
I think this code is an excellent specimen of the strengths and weaknesses of C strings.
The main function is fantastically efficient.
But actually has to scan the string twice because C doesn't intrinsically provide a O(1) way of obtaining the length of a string!