I have this function that take a sentence and reverse each words. I have to modify the value in-place and the return value should be Null. I can't modify the main:
int main()
{
char *string= "hello";
reverser(string);
printf("%s\n", string);
}
In my reverser
function i use strtok
which require a non-const char*
char* reverser(char *sentence) {
char *copy = strdup(sentence);
char *string;
int i, j;
for(j = 0; (string = strtok(j ? NULL : copy, " ")) != NULL; j++)
for(i = strlen(string) - 1; i >= 0; --i, j++)
sentence[j] = string[i];
return NULL;
}
Even using strdup it doesn't work and I can't figure out why... Someone has any suggestion to make it work? thank you
Replace char *string= "hello";
with char string[] = "hello";
Otherwise string
will be unmodifiable, and it would be impossible for the reverser function to work. (given that it will always return NULL)