I'm doing a file reading. The contents of the file is saved into a subject node called head. In order to perform dynamic node creation, I equated the temp = *head (on line 48). Upon printing, calling print(head) on line 34, the program crashed.
I debugged it and found a segmentation fault on printing so I added line 50 and 51 for manual debugging. The contents of ctemp can be printed, but not the original node *head. Clearly it is not updated.
What's the problem with line 48? Why can't the value of head be changed? What do you think am I doing wrong?
*added txt && cpp attachments
Code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef struct cell {
int row, bit;
struct cell *next;
}cell;
typedef struct course{
int col;
char name[3];
struct cell* rcell;
struct course *next;
}course;
typedef struct subject{
int col;
char name[3];
struct student* student;
struct subject *next;
}subject;
typedef struct student{
int index;
char name[3];
struct student *next;
}student;
void readfile(subject**);
void print(subject*);
void _free(subject**);
int main(void) {
subject* head = NULL;
readfile(&head);
print(head);
_free(&head);
free(head);
}
void readfile(subject** head) {
int column = 0, row = 0, ctotal = 0;
char cname[3], sname[3], c;
ifstream ifile("schedule.txt");
subject *ctemp = NULL;
student *stemp = NULL;
if(ifile.is_open()){
ctemp = *head;
while(ifile >> cname) {
ctemp = new subject;
strcpy(ctemp->name, cname);
cout << "\nctemp " << ctemp->name << " ";
cout << "\nhead "<< (*head)->name << " ";
ctemp->col = column++;
stemp = ctemp->student;
while(ifile >> sname) {
c = ifile.get();
if(c == '\n') break;
stemp = new student;
stemp->index = row++;
strcpy(stemp->name, sname);
cout << stemp->name << " ";
stemp->next = NULL;
stemp = stemp->next;
}
row = 0;
ctemp->next = NULL;
ctemp = ctemp->next;
ctotal++;
}
} else {
cout << "\nfile error";
}
ifile.close();
}
void print(subject *head) {
while(head) {
cout << endl << head->name << " ";
while(head->student) {
cout << head->student->name << " ";
head->student = head->student->next;
}
head = head->next;
}
}
void _free(subject** head) {
subject* ctemp = NULL;
student* stemp = NULL;
while(*head) {
ctemp = *head;
while((*head)->student) {
stemp = ctemp->student;
(*head)->student = (*head)->student->next;
stemp->next = NULL;
free(stemp);
}
*head = (*head)->next;
ctemp->next = NULL;
free(ctemp);
}
}