C:strtok的首要previous数组值? [英] C: strtok overriding previous array values?

查看:80
本文介绍了C:strtok的首要previous数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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..

我的输出如下:

0普拉特elyn 193)760-4405

0 Pratt elyn 193)760-4405

1普拉特伊夫林

2普拉特velyn

2 Pratt velyn

3普拉特velyn(193)760-4405

3 Pratt velyn (193)760-4405

4普拉特velyn 93)760-4405

4 Pratt velyn 93)760-4405

5普拉特(193)760-4405

5 Pratt (193)760-4405

6普拉特elyn 3)760-4405

6 Pratt elyn 3)760-4405

等等......

输出应该是,

0阿科斯塔纳丁(752)596-6540

0 Acosta Nadine (752)596-6540

1奥尔福德斯凯勒(635)736-7827

1 Alford Skyler (635)736-7827

2艾利森·劳伦斯(475)886-5725

2 Allison Lawrence (475)886-5725

3科林·阿尔瓦雷斯(659)911-6629

3 Alvarez Colin (659)911-6629

4球卡德曼(328)898-9532

4 Ball Cadman (328)898-9532

5巴拉德阿贝尔(853)190-0868

5 Ballard Abel (853)190-0868

...

99普拉特伊夫林(193)760-4405

99 Pratt Evelyn (193)760-4405

正如你所看到的,普拉特伊夫林(193)760-4405是我从

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

我是相当新的C,并没有解释什么错误将AP preciated!

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

推荐答案

您需要复制要保存的字符串。像...

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, " "));

通过您的code,字符数组正在重新用于所有线条和它的指针设置到 card_array 成员。当你阅读新的生产线,previous指针也将获得新的数据。最终,每个人​​都会有来自最后一行读取字符。

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.

另外,与你的code的另一个问题是,你正在返回本地阵列 - 这是错误的。

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

这篇关于C:strtok的首要previous数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆