I'm just learning C and I'm trying to write a function that reverses a char-array (string) not with indices, but via a pointer and without malloc:
#include <stdio.h>
#include <string.h>
char* reverse(char* chararray)
{
char *forward = chararray;
char *reversed = &chararray[strlen(chararray)-1];
while (reversed > forward) {
char revTmp = *reversed;
char fwdTmp = *forward;
*reversed-- = fwdTmp;
*forward++ = revTmp;
}
return reversed;
}
int main()
{
char string[] = "dlrow olleh";
printf("%s\n",reverse(string));
return 0;
}
the output for now is world
and should be hello world
- but it breaks in the middle and I have no idea, why. There must be something I missed.