C: strtok overriding previous array values?

不想你离开。 提交于 2019-12-11 04:12:52

问题


card * load_rolodex(FILE *read_file)
{
        int array_index = 0;
        char line [LINE_MAX];

        card *card_array = malloc(sizeof(card) * upper_bound);

        while (fgets(line, LINE_MAX, read_file)!= NULL)
        {
                card_array[array_index].last_name = strtok(line, " ");
                card_array[array_index].first_name = strtok(NULL, " ");
                card_array[array_index].phone_number = strtok(NULL, " ");
                size++;
                array_index++;
        }
        return card_array;
}

I am trying to save each token to values in a struct array.

I'm reading from a file with the following format

lastname firstname number lastname firstname number etc..

My output is as follows:

0 Pratt elyn 193)760-4405

1 Pratt Evelyn

2 Pratt velyn

3 Pratt velyn (193)760-4405

4 Pratt velyn 93)760-4405

5 Pratt (193)760-4405

6 Pratt elyn 3)760-4405

etc...

The output should be,

0 Acosta Nadine (752)596-6540

1 Alford Skyler (635)736-7827

2 Allison Lawrence (475)886-5725

3 Alvarez Colin (659)911-6629

4 Ball Cadman (328)898-9532

5 Ballard Abel (853)190-0868

...

99 Pratt Evelyn (193)760-4405

As you can see, Pratt Evelyn (193)760-4405 is the last line of the file I am reading from,

I'm fairly new to C, and any explanation as to what is going wrong would be appreciated!


回答1:


You need to duplicate the strings you are saving. Like ...

card_array[array_index].last_name = strdup(strtok(line, " "));
card_array[array_index].first_name = strdup(strtok(NULL, " "));
card_array[array_index].phone_number = strdup(strtok(NULL, " "));

With your code, character array line is being re-used for all lines and its pointers are set into the card_array members. As you read new line, previous pointers will also get new data. Ultimately everyone will have characters from last line read.

Also, another problem with your code is you are returning local array - line which is wrong.



来源:https://stackoverflow.com/questions/27263728/c-strtok-overriding-previous-array-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!