-1

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

sworwitz
  • 19
  • 7
  • 1
    Did you know that `strdup` already copies `sentence`'s contents into the `copy`'s buffer? – nbro Nov 07 '16 at 19:07
  • 4
    Sentence is pointing to a string literal. It shall not be modified. – 2501 Nov 07 '16 at 19:08
  • By the way, you're returning always `NULL` from `reserver`. Not even looked at your for loop, but these should already be a few bugs that you should fix. – nbro Nov 07 '16 at 19:08
  • Indeed, return the string that was `strdup`ed. Then you would have `printf("%s\n", reverser(string));` BTW did you read the man page for `strdup`? You already made a copy before you use `strcpy` to do the same thing. Moreover your implementaion of `strtok` is ugly and hard to follow. The idiomatic way is to use a `while` loop based on the pointer returned by `strtok`. – Weather Vane Nov 07 '16 at 19:15
  • Sorry I forgot to delete the strcpy... I just edited it. Btw the behavior and the question are the same – sworwitz Nov 07 '16 at 19:24
  • well, beauty is subjective – sworwitz Nov 07 '16 at 20:06
  • 1
    "strtok doesn't work with non-const char argument" --> `strtok()` is working fine. Attempting to modify `"hello"` is not OK. Try `char string[] = "hello";` and free your allocated data when done with it. – chux - Reinstate Monica Nov 07 '16 at 21:28
  • 3
    If you can't modify that main code, your task is impossible (without cheating). – melpomene Nov 07 '16 at 22:27
  • @melpomene I second that statement. – Dellowar Nov 07 '16 at 22:36

1 Answers1

0

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)

Dellowar
  • 3,160
  • 1
  • 18
  • 37