Reputation: 1
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
}
Upvotes: 0
Views: 186
Reputation: 1
I figured out an answer. I wasn't allocating memory in main so something was happening to it when I tried to pass the pointer. After I allocated it in main I was able to create a double pointer that points to the address of the first pointer and then pass that around. Manipulating the linked list by dereferencing my double pointer (*pointer)->item. Thanks for the help I got the idea from here.
Upvotes: 0
Reputation: 1313
int main(List **points)
does not work. It should be:
int main(int argc, char *argv[])
See main(int argc, char *argv[]) or What should main()
return in C and C++? for more details.
points->Load();
does not work - if your function Load returns a pointer then it should be:
points=Load();
I think there is also an issue with you repeated use of malloc in the loop in the function. It seems to me that you want a long list, but I think it will be impossible to free all the memory you have allocated at the end of the program, because you only return the address of head.
Upvotes: 1