【发布时间】:2016-05-16 19:41:44
【问题描述】:
#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
数据 2:影子,19
数据 3:龙,12
但这就是发生的事情。
数据1:精神,6
数据 2:精神,19
资料 3:精神,12
为什么 save 变量在移动而 *data 没有?我应该添加什么以及放置在哪里?谢谢您的帮助。 [对不起,不必要的变量,它是整体的一部分]
【问题讨论】:
-
strtok 返回一个指向 filestr 的指针,link->data 指向 filestr,如果你覆盖了 filestr,你也覆盖了 link->data ... 使用 malloc+strcpy 或 strdup 将 strtok 返回的数据复制到链接->数据
标签: c struct linked-list