[英]Program crashes when trying to return pointer to linked list
我試圖返回指向main的鏈表的指針,以便可以將其傳遞給其他函數,每次嘗試加載以傳遞任何東西時,程序崩潰並弄亂了文件輸出,但我無法找出原因。
#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)
不起作用。 它應該是:
int main(int argc, char *argv[])
請參見main(int argc,char * argv [])或main()
在C和C ++中應該返回什么? 更多細節。
points->Load();
不起作用-如果您的函數Load返回一個指針,那么它應該是:
points=Load();
我認為在函數的循環中重復使用malloc還有一個問題。 在我看來,您需要一個長列表,但是我認為不可能在程序末尾釋放所有已分配的內存,因為您只返回head的地址。
我想出了一個答案。 我沒有在main中分配內存,所以當我嘗試傳遞指針時發生了一些事情。 在main中分配了它之后,我可以創建一個指向第一個指針地址的雙指針,然后將其傳遞。 通過取消引用我的雙指針(* pointer)-> item來處理鏈接列表。 感謝您的幫助,我從這里得到了這個主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.