I'm writing a program in which a function that reverses each word in a string. When I call the function, it will pass the pointer to source string and then return the pointer to modified string.
input: Why always me? output: yhW syawla ?em
But for some reason, it is not working. No errors. And logic seemed fine to me (i'm not that good with c, btw) Here's my code:
char *reverse_words(char *source_string)
{
char *startW, *endW;
startW = source_string;
while(*startW != '\0')
{
while(*startW == ' ')
startW++; //Skip multiple spaces in the beginning
endW = startW;
while(*endW != ' ' || *endW != '\0')
endW++;
char *_start = startW;
char *_end = endW - 1;
char temp;
while(_end > _start)
{
temp = *_start;
*_start++ = *_end;
*_end++ = temp;
}
startW = endW;
}
return source_string;
}
void main() {
char *s;
s = malloc(256);
gets(s);
printf("%s\n", s);
char *r = reverse_words(s);
printf("\nReversed String : %s",r);
free(s);
free(r);
}
Also, i'm using codeblocks IDE. After I input my string, it prints it back (scanf and printf in main) and after that, the program stops working.
Any help would be appreciated.
rev=source_string
just copy the reference and not actual string – GoldRoger