#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
檢索鏈接列表中的指針元素的數據
爲什麼該保存變量是移動而*數據是不?我應該添加什麼以及在哪裏放置?謝謝您的幫助。 [對不必要的變量抱歉,它是整體的一部分]
歡迎來到Stack Overflow! [請參閱此討論,爲什麼不在'C'中投射'malloc()'和family的返回值。](http://stackoverflow.com/q/605845/2173917)。 –
strtok返回一個指向filestr,link-> data points的指針到filestr,如果覆蓋filestr你也覆蓋link-> data ...使用malloc + strcpy或strdup將strtok返回的數據複製到link-> data – Picodev