Reverse a string in place without a second buffer. It must also work for an empty string.
#include <stdio.h>
#include <string.h>
void reverse(char *s) {
size_t n = strlen(s);
if (n == 0)
return; /* s + n - 1 would be before the string */
for (char *l = s, *r = s + n - 1; l < r; l++, r--) {
char t = *l;
*l = *r;
*r = t;
}
}
int main(void) {
char a[] = "LearnFrenzy", b[] = "";
reverse(a);
reverse(b);
printf("%s [%s]\n", a, b);
return 0;
}
yznerFnraeL []
Swap the outer pair and move both pointers inwards. The empty-string check matters: with n = 0, s + n - 1 would point before the array, which is undefined behaviour.