How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?
I like Evgeny's K&R answer. However, it is nice to see a version using pointers. Otherwise, it's essentially the same:
#include
#include
#include
char *reverse(char *str) {
if( str == NULL || !(*str) ) return NULL;
int i, j = strlen(str)-1;
char *sallocd;
sallocd = malloc(sizeof(char) * (j+1));
for(i=0; j>=0; i++, j--) {
*(sallocd+i) = *(str+j);
}
return sallocd;
}
int main(void) {
char *s = "a man a plan a canal panama";
char *sret = reverse(s);
printf("%s\n", reverse(sret));
free(sret);
return 0;
}