読み込んだファイルの内容をlistprint関数を呼び出して表示しようとしているのですがHead-以降は何も表示されずSegmentation fault:11と表示されてしまいます。メモリの確保とかはできていると思うのですがどこがいけないのでしょうか。Record型の変数が標準入力と同じ変数名がダメなのかと思い別のものに置き換えましたが同じエラーが出てきました。
c
1#include <stdio.h> 2#include <stdlib.h> 3#include "stulist.h" 4 5/*Stulist1.datを出力する関数*/ 6void stuprint(void); 7int main() 8{ 9 int i,num; 10 Record data,data2; 11 FILE *fp; 12 13 head = make_1node(data, NULL); 14 listprint(); 15printf("Head-\n"); 16/*Student.datから読み込んで、listprintを呼び表示*/ 17while(1){ 18 fp=fopen("Student1.dat","r"); 19 if(fscanf(fp,"%d %s %d %d %d",&data2.id,data2.name,&data2.score[0],&data2.score[1],&data2.score[2])==EOF)break; 20 fprintf(fp,"%d %s %d %d %d\n",data2.id,data2.name,data2.score[0],data2.score[1],data2.score[2]); 21 listprint(); 22} 23/*標準入力*/ 24 while (1) { 25 printf("Insert new data:(ID name score1 score2 score3)->"); 26 if(scanf("%d %s %d %d %d",&data.id,data.name,&data.score[0],&data.score[1],&data.score[2])==EOF)break; 27 if (insert(data) == NULL) printf("Data %d is already on the list\n", data.id); 28 listprint(); 29 } 30 fclose(fp); 31 return 0; 32} 33 34NodePointer insert(Record keydata) 35{ 36 NodePointer newnode; 37 38 if (finditem(keydata.id) == NULL) { 39 newnode = make_1node(keydata, head->next);//make_1nodeで確保したメモリのアドレスを代入する 40 head->next = newnode; 41 42 return newnode; 43 } 44 else return NULL; 45} 46 47void listprint(void) 48{ 49 NodePointer n; 50 51 for (n = head->next; n != NULL; n = n->next) { 52 printf(" %10d %-13s %3d %3d %3d \n", n->data.id,n->data.name,n->data.score[0],n->data.score[1],n->data.score[2]); 53 } 54 printf("\n"); 55} 56 57NodePointer finditem(int keydata) 58{ 59 NodePointer n; 60 61 for (n = head; n->next != NULL; n = n->next) { 62 if (n->next->data.id == keydata) return n;//以前にあるものとアドレスが一致したら抜け出す 63 } 64 65 return NULL; 66} 67 68NodePointer make_1node(Record keydata, NodePointer p) 69{ 70 NodePointer n;//node型のポインタn 71 72 /*struct nodeの領域を確保してnという名前にする、そしてその先頭のアドレスを返す、これがNULLならError*/ 73 if ((n = (NodePointer)malloc(sizeof(struct node))) == NULL) { 74 printf("Error in memory allocation\n"); 75 exit(8); 76 } 77 78 n->data = keydata; 79 n->next = p; 80 81 return n; 82}
c
1/* struct declaration */ 2typedef struct { 3 int id; 4 char name[15]; 5 int score[3]; 6}Record; 7 8typedef struct node *NodePointer; 9 10struct node{ 11 Record data; 12 NodePointer next; 13}; 14 15/* prototype declaration */ 16NodePointer insert(Record); 17NodePointer finditem(int); 18void listprint(void); 19NodePointer make_1node(Record , NodePointer); 20 21/* Global Variable head */ 22NodePointer head; 23
Student1.dat
1251001 Yamada 83 67 90
1251022 Watanabe 90 75 89
1251033 Saito 50 55 45
1251004 Sato 60 70 83
1251007 Nagashi 81 80 72
1251081 Matsui 90 85 89
1251098 Kudo 95 90 94
1251123 Ota 65 70 72
1251164 Egawa 61 94 71
1251200 Higashio 61 94 55
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/03 12:40 編集
2018/11/03 12:36 編集
2018/11/03 12:48 編集
2018/11/03 13:45
2018/11/03 23:27
2018/11/03 23:49 編集