#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
ポインタ要素でリンクリストのデータを取得する
はなぜ保存変数が移動していること、および*データがないのですか?私は何を追加し、どこに置くべきですか?助けてくれてありがとう。 [不必要な変数を残して申し訳ありません、それは全体の一部です]
ようこそスタックオーバーフロー! ['malloc()'と 'C 'のファミリーの戻り値をキャストしない理由についてのこのディスカッションを参照してください。](http://stackoverflow.com/q/605845/2173917)。 –
strtokは、filestrを指すポインタを返します。filestrを上書きすると、link-> dataはfilestrになります。strtokから返されたデータをlink-> dataにコピーするには、malloc + strcpyまたはstrdupを使用します。 – Picodev