Мое предложение
#include <stdio.h> // printf
#include <string.h> // strlen
void swap(char* a , char* b)
{
char tmp;
tmp=*a;
(*a) = (*b);
(*b) = tmp;
}
void ReverseInPlace(char * x)
{
char * end = x;
int i,j,length;
char temp;
length = strlen(x);
//swap 1st with last, then 2nd with last-1, etc. Till we reach the middle of the string.
for(i=0,j=length-1 ; i<j ; ++i,--j)
swap( &x[i] , &x[j]);
}
main (){
char str[] = "123456789";
ReverseInPlace(str);
//ReverseInPlace("1234"); // this would lead to error, because "1234", can not be modified
printf("%s\n",str);
}
После достижения середины вы должны поменять местами элементы, которые уже были заменены предыдущими итерациями.Для иллюстрации:
char* x = "1234";
1 2 3 4
4 2 3 1
4 3 2 1 // already reversed!
4 2 3 1
1 2 3 4 // if we continue till i==length-1 && j=0 , then we just get where we started