Hi guys! I've been having problem with my code below:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct students{
char studentName[3];
struct students *next;
}student;
typedef struct courses{
char courseCode[3];
student *studentPtr;
struct courses *next;
}course;
main(){
int choice, numCourse, i=0, j, c, d;
char fileName[100], courseLists[numCourse][9999], temp[9999];
course *head = NULL, *ptr;
student *headStud, *newStud;
printf("Enter number of courses: ");
scanf("%d", &numCourse);
printf("Enter course name followed student names: \n");
for(i=0;i<numCourse;i++){
scanf(" %[^\n]", temp);
strcpy(courseLists[i], temp);
j = 0;
course *newCourse = (course *)malloc(sizeof(course));
while(courseLists[i][j]!=' '){
newCourse->courseCode[j] = courseLists[i][j];
j++;
}
if(head==NULL){
head = newCourse;
ptr = newCourse;
}else{
while(head->next!=NULL) head = head->next;
head->next = newCourse;
}
headStud = NULL;
if(headStud==NULL){
newStud = (student *)malloc(sizeof(student));
headStud = newStud;
newCourse->studentPtr = newStud;
}
for(d=4;d<strlen(courseLists[i]);d++){
newStud->studentName[c] = courseLists[i][d];
c++;
if(c==3){
newStud = (student *)malloc(sizeof(student));
c = 0;
while(headStud->next!=NULL) headStud = headStud->next;
headStud->next = newStud;
d++;
}
}
}
while(ptr!=NULL){
printf("%s ", ptr->courseCode);
while(ptr->studentPtr!=NULL){
printf("%s ", ptr->studentPtr->studentName);
ptr->studentPtr = ptr->studentPtr->next;
}
printf("\n");
ptr = ptr->next;
}
}
The input goes like this:
c01 jjd kks jjd
c02 jdj mms dds
Yes. This is actually an Exam Scheduling Problem where c01 is the course name, jjd, kks, etc. are the initials of the students.
course names are stored in courseCode element of the course linked list, while student names are stored in studentName element of the student linked list.
Sometimes the code works, sometimes it says segmentation fault (core dumped)
Help please!