gpt4 book ai didi

c - 使用指针元素检索链表中的数据

转载 作者:太空宇宙 更新时间:2023-11-04 02:36:03 25 4
gpt4 key购买 nike

#include<stdio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct trial{
char *data;
int save;
struct trial *next;
};

struct trial *head = NULL;

int main (){
int x, ctr, y;
char filestr[500];
char *data, *save, *filestr2;
FILE *fp;
fp = fopen("Untitled1.txt", "r");
printf("Count: ");
scanf("%d", &x);
while(x > 0){
if(fgets(filestr, sizeof(filestr), fp) != NULL){
data = strtok(filestr, " ");
filestr2 = strtok(NULL, "");
save = strtok(filestr2, "");
printf("%s, %s", data, save);
struct trial *link = (struct trial*) malloc(sizeof(struct trial));
link->data = data;
link->save = atoi(save);
link->next = head;
head = link;
}
x--;
}
printf("\n");
struct trial *ptr = head;
ctr = 0;
while(ptr != NULL){
printf("Data %d: %s, %d\n", ctr + 1, ptr->data, ptr->save);
ptr = ptr->next;
ctr++;
}
return 0;
}
/*Untitled1.txt is as follows
dragon 12
shadow 19
spirit 6
wiser 4
civil 8
fairy 7
*/

现在问题来了,当 x = 3 时;应该是:
数量:3
龙,12
影子,19岁
精神, 6

数据1:精神,6
数据二:阴影,19
数据3:龙,12

但事情是这样的。
数据1:精神,6
资料二:精神,19
数据3:精神,12

为什么 save 变量在移动而 *data 没有?我应该添加什么以及放置在哪里?谢谢您的帮助。 [对不起,不必要的变量,它是整体的一部分]

最佳答案

如前所述,strtok 返回一个指向其第一个参数的指针。要修复此错误,请复制您感兴趣的部分。只需替换

link->data = data;

link->data = strdup(data);

记得释放链接->数据。

关于c - 使用指针元素检索链表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37261975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com