Here is student.txt file with some information and I took them to the array and I created a sorted linked list using the array, but it is not listing any information. I could not find why it is happening! Here is the onlineGDB session.
Who can find my mistake in the code and explain it?
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct studInfo {
int studNr;
char studName[12];
int grade;
};
struct node {
struct studInfo info;
struct node *link;
};
typedef struct node *NODEPTR;
NODEPTR getnode(void);
void fileIntoArray(struct studInfo allStudent[],int *num);
void sortByNum(struct studInfo allstudent[], NODEPTR *, int num);
void list(NODEPTR);
int main() {
struct studInfo allStudent[150];
NODEPTR headNum, headName;
int choice;
int num;
fileIntoArray(allStudent, &num);
sortByNum(allStudent, &headNum, num);
list(headNum);
return 0;
}
void fileIntoArray(struct studInfo allStudent[], int *num) {
FILE *ptr = fopen("student.txt", "r");
int i = 0;
while (!feof(ptr)) {
fscanf(ptr, "%d%s%d", &allStudent[i].studNr,
allStudent[i].studName, &allStudent[i].grade);
i++;
}
*num = i;
fclose(ptr);
}
void sortByNum(struct studInfo allStudent[], NODEPTR *headNum, int num) {
NODEPTR head, p, save, prev;
head = NULL;
for (int i = 0; i <= num; ++i) {
p = getnode();
p->info = allStudent[i];
if (head = NULL) {
head = p;
p->link = NULL;
} else {
if (p->info.studNr < head->info.studNr) {
p->link = head;
head = p;
} else {
save = head;
while ((save->info.studNr < p->info.studNr) &&(save != NULL)) {
prev = save;
save = save->link;
if (save == NULL) {
prev->link = p;
p->link = NULL;
} else {
p->link = prev->link;
prev->link = p;
}
}
}
}
}
*headNum = head;
}
void list(NODEPTR headNum) {
NODEPTR p = headNum;
int line = 0;
while (p->link != NULL) {
line++;
if (line > 25) {
printf("Tab a button\n");
getchar();
line = 1;
}
printf("%d %d %s %d\n", line, p->info.studNr,
p->info.studName, p->info.grade);
p = p->link;
}
}
NODEPTR getnode() {
NODEPTR q;
q = (NODEPTR)malloc(sizeof(struct node));
return(q);
}
There are multiple problems:
in
sortByNum, the loopfor (int i = 0; i <= num; ++i)runs one iteration too far. You should usei < numto iterate exactlynumtimes.in
sortByNum(), the testif (head = NULL)is incorrect. You should write:while (!feof(ptr))is incorrect too. You should instead write:you should pass the array length to
fileIntoArrayso it can avoid writing beyond the end of the array.the
nodestructures should have pointers to thestudInfoentries in the array, not copies.the node insertion code is too complicated and probably incorrect.
in
list, the testwhile (p->link != NULL)will cause a crash if the list passed as argument is empty.fileIntoArrayandsortByNumshould return a result instead of storing it to a caller variable via a pointer.hiding pointers behind typedefs such as
NODEPTRis not recommended. Usestruct node *ptror possibly definenodeas atypedefforstruct nodeand writenode *ptr.Here is a modified version: