0

My problem is I can't make my program to read char *word in function read_word_details and parse it back to solve_task_1 function.

  void read_word_details(int *x, int *y, int *orientation, char *word) {
        char *p, input[20];
        fgets(input, 20, stdin);
        p = strtok(input, " ");
       *x = string_to_number(p);
        p = strtok(NULL, " ");
        *y = string_to_number(p);
        p = strtok(NULL, " ");
        *orientation = string_to_number(p);
        p = strtok(NULL, " ");
        word = p;
    }

    void solve_task_1() {
        char input[20], *p;
        fgets(input, 20, stdin);
        p = strtok(input, "a");
        int n = string_to_number(p);
        for (int i = 1; i <= n; i++) {
            int x, y, orientation;
            char *word;
            read_word_details(&x, &y, &orientation, word);
            printf("%d %d %d %s\n", x, y, orientation, word);
        }
    }

My input is 1 1 2 3 asd, and my output is 1 2 3 HH9u[]A\A]A^A_ff., instead of 1 2 3 asd.

Edit: My string_to_number function is:

int string_to_number(char *p)
{
    int length = strlen(p);
    int sum = 0;
    for (int i = 0; i < length; i++) {
        if (p[i] >= '0' && p[i] <= '9') {
        sum *= 10;
        sum += p[i] - '0';
        }
    }
    return sum;
}
  • What is `string_to_number`?. [Edit] and show a [mcve] – Jabberwocky Dec 03 '20 at 16:51
  • Parameters act like local variables, so `word = p;` only has a local effect. Also, since `p` is pointing within a local array variable, it is no longer valid when the function returns. You could do `strcpy(word, p);` but the caller would need to provide the storage. Or you could change the parameter type to `char **word` and set `*word = malloc(strlen(p)+1);` `strcpy(*word, p);`. – Ian Abbott Dec 03 '20 at 16:59
  • @IanAbbott I tried and the result is Segmentation fault. – Stefan Radulescu Dec 03 '20 at 17:18
  • You probably never provided storage for `word`. In `solve_task_1`, if you change `char *word;` to `char word[20];` this should provide sufficient storage. Then the `strcpy` I mentioned in my earlier comment will work. – Ian Abbott Dec 03 '20 at 17:21
  • @IanAbbott, I tried this, and the result for `word` is a random string with 2 chars. – Stefan Radulescu Dec 03 '20 at 17:24

0 Answers0