尝试返回指向链接列表的指针时程序崩溃

时间:2015-12-06 00:02:41

标签: c

我正在尝试将指向链接列表的指针返回到 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,&current->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

   }

2 个答案:

答案 0 :(得分:1)

int main(List **points)

不起作用。它应该是:

int main(int argc, char *argv[])

有关详细信息,请参阅main(int argc, char *argv[])What should main() return in C and C++?

points->Load();   

不起作用 - 如果你的函数Load返回一个指针,那么它应该是:

points=Load();

我认为在函数循环中重复使用malloc也存在问题。在我看来,你想要一个很长的列表,但我认为你不可能释放你在程序结束时分配的所有内存,因为你只返回头部的地址。

答案 1 :(得分:0)

我找到了答案。我没有在main中分配内存,所以当我试图传递指针时发生了一些事情。我在主要分配后 我能够创建一个指向第一个地址的双指针 指针,然后传递它。通过解除引用来操作链表 我的双指针(*指针) - &gt;项目。感谢您的帮助,我从这里得到了这个想法。

相关问题