I wrote this program that writes some data on a .txt and then reads it and create a list by sorting in alphabetical order. The program seems to work but soon after I see the output it crashes. Could you help me understand why?
I get this error:
warning: assignment to 'struct node *' from incompatible pointer type 'list' {aka 'struct nodeList *'} [-Wincompatible-pointer-types]|
Proably this is a very basic issue about pointers but can't understand where's the problem. Any advice about the function sort is welcome. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct {
char name[20];
int time;
}elem;
typedef struct nodeList{
elem el;
struct node *next;
}node;
typedef node *list;
bool isless(elem e1, elem e2){
return (strcmp(e1.name, e2.name)<0);
}
void sort(list *l, elem e){
list t;
list prev;
list cursor;
t=(node*)malloc(sizeof(node));
if(t==NULL){
printf("Error malloc
");
system("pause");
exit(1);
}
t->el=e;
if(*l==NULL){
*l=t;
}
else{
prev=NULL;
cursor=*l;
while(cursor!=NULL){
if(!isless(cursor->el,t->el)){
if(prev==NULL){
*l=t;
t->next=cursor;
}
else{
prev->next=t;
t->next=cursor;
}
break;
}
prev=cursor;
cursor=cursor->next;
}
if(cursor==NULL){
prev->next=t;
t->next=cursor;
}
}
}
void stamp(list l){
if(l==NULL){
printf("Empty list
");
}
while(l!=NULL){
printf("%s%d
",(l->el).name,(l->el).time);
l=l->next;
}
}
int main()
{
elem e;
int T;
char N[20];
FILE *f1;
list head=NULL;
f1=fopen("STORAGE.TXT","w");
//user input
while(1){
printf("Insert a name (or write stop):");
scanf("%s",N);
if(strcmp(N,"stop")==0)
break;
printf("Insert a time:");
scanf("%d",&T);
strcpy(e.name,N);
e.time=T;
fwrite(&e,sizeof(elem),1,f1);
}
fclose(f1);
//create and sort a list in alphabetical order
f1=fopen("STORAGE.TXT","r");
while(fread(&e,sizeof(elem),1,f1)>0)
sort(&head,e);
fclose(f1);
//stamp list
stamp(head);
return 0;
}
question from:
https://stackoverflow.com/questions/65919101/program-to-sort-list-in-alphabetical-order-crashes 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…