Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 删除链接列表中的所有节点_C_Linked List - Fatal编程技术网

C 删除链接列表中的所有节点

C 删除链接列表中的所有节点,c,linked-list,C,Linked List,有人知道这个再创造的功能有什么问题吗?它不会删除所有节点 struct contact { char FirstName[41]; char LastName[41]; int id; struct contact *next; }; void ClearList (struct contact *person) { struct contact *temp = person; if (person == NULL) return; el

有人知道这个再创造的功能有什么问题吗?它不会删除所有节点

struct contact
{
    char FirstName[41];
    char LastName[41];
    int id;
    struct contact *next;
};

void ClearList (struct contact *person)
{
    struct contact *temp = person;
    if (person == NULL) return;
    else
    {
        person = person->next;
        free(temp);
        ClearList(person);
    }
}
这是我的主要功能

void main()
{
    struct contact *person = malloc(sizeof(struct contact));
    strcpy (person->FirstName, "John");
    strcpy (person->LastName, "Doe");
    person->id = 10;

    person->next = malloc(sizeof(struct contact));
    strcpy (person->next->FirstName, "Will");
    strcpy (person->next->LastName, "Smith");
    person->next->id = 20;
    person->next->next = NULL;

    PrintList(person);
    ClearList(person);
    PrintList(person);
}
当我在调用ClearList后调用PrintList时,它仍然会打印出一些杂乱的内容,我该如何解决这一问题?

所有节点都会被删除,但您永远不会清除任何指针。因此,您所做的是取消对无效指针的引用,从而导致错误


free
函数不会自动设置指向
NULL

的指针,我真的不喜欢链表上的这种递归删除。如果您的链表有100个元素,那么您将在堆栈中执行100个函数,并且可能会崩溃

我建议重写如下:

void ClearList (struct contact *person)
{
   while( person != NULL )
   {
        struct contact * temp = person
        person = person->next;
        free(temp);
   }
}
约阿希姆有正确的答案。尽管我们已经清除了person指向的内存,“ClearList”无权将原始指针设置为NULL。因此,您需要使ClearList接受一个双指针,以便它可以将指针设置为NULL,或者在调用ClearList后将“person”设置为NULL

双指针示例,使用ClearList(&person)调用


struct contact
的定义是什么?您是否尝试过在调试器中逐行遍历代码?您如何知道它不会删除所有节点?
void ClearList(struct contact*person){if(person){ClearList(person->next);free(person);}
ClearList(person);PrintList(person)发布后使用的
无效。当我再次调用PrintList时,它会打印出姓氏和id,但名字是messyso我应该将temp=NULL吗?至少这不会有什么害处。我认为在执行
Clearlist(person)之后,应该将main()中的
person
设置为NULL
所以当删除从最后一个到第一个发生时,就不会有指针(下一个)需要清除??我说的对吗?
void ClearList (struct contact ** list)
{
   struct contact *person = *list;
   while( person != NULL )
   {
        struct contact * temp = person
        person = person->next;
        free(temp);
   }
   *list = NULL;
}