I'm trying to return a pointer to a linked list to main so that I can pass it around to other functions.Anytime I try to get load to pass anything the program crashes and it messes up the file output.I just can't figure out why.
#include <stdio.h>
#include <stdlib.h>
struct list{ //creating linked list
char furn[128];
int priority;
struct list *next;
};
typedef struct list List; //typedef for list
//creating pointer for head of list
List **Load();
int main(List **points)
{
points->Load(); //crashes here no if I try to set Load to anything, works fine and prints okay if I don't
}
List ** Load()
{ List *head;
List *current; //so we can build and navigate list
List *new;
FILE *fin, *fout; //so that we can start file manipulation
char name[]= "California.txt" ;
fin=fopen(name, "r");
new=malloc((sizeof(List))); //creating list
head=new;
while(current->next!=NULL)
{
current=new;
new=malloc((sizeof(List)));
fscanf(fin,"%s %d",current->furn,¤t->priority); //reading and populating list
current->next=new;
if(feof(fin))
current->next=NULL;
}
current=head;
printf("%s %d",current->furn,current->priority);
while(current->next!=NULL)
{
printf("Starting");
printf("%s %d",current->furn,current->priority);
current=current->next;
}
List **points=&head;
return points; //Returning so we can have a pointer to the list
}
int main(List **points)work?points->Load();shouldn't even compile, no matter how permissive your compiler settings. This isn't C (it's not C++ either). If it does somehow compile, the crash is most likely becausepoints->is trying to dereference the integer1(or a similar small number that isn't a valid address), because the first argument tomainis a small integer on any normal OS.Load()return aList **seems implausible; aList *is more orthodox, at least. In the function, you have a local (automatic) variableList *head;and at the end you haveList **points=&head; return points;which means you're returning the address of a local variable, which is always a bad idea. Change the function to returnList *and simply usereturn head;would give you a fighting chance if everything else was reasonably kosher. The definition ofmain()as it stands is anything but kosher; the use ofpoints->Load()inmain()is not going to work.