c - 删除列表中唯一的值后显示列表时出现错误处理中断

标签 c linked-list printf unhandled-exception

两种方法都工作正常,但在删除所有节点后,我无法停止未处理的异常,我在显示中添加的标签应该可以解决此问题,但我仍然遇到异常:

  void DisplayAllEmp(struct node* head){

    struct node *temp;
    temp =(struct node*)malloc(sizeof(struct node));
    temp = head;
    if( temp == NULL ){ //check if theres anything in the list
     delerr: printf("\nDatabase is empty.\n"); // notify the DB is empty
    }
    else{   
        while( temp!= NULL ) //loop through all employees and print them out
        {
            if( temp->empId == NULL ){ goto delerr; } // for catching error following delete employee when you display the DB
            printf("\nId: %d Address: %s Department: %d DOJ: %d/%d/%d Salary: %d Email: %s", temp->empId, temp->address, temp->depart, temp->day,temp->mounth,temp->year, temp->salary, temp->email); // show the employee
            temp = temp->next;
        }//while end
    }

}   


 void DeleteEmp(struct node* head, int tempID){
    struct node *curNode = head;
    struct node *prevNode = curNode;
    while (curNode != NULL) {
        if(curNode->empId == tempID) {
            prevNode->next = curNode->next;
            if (prevNode){// remove the node from the list
            prevNode->next = curNode->next;   
            }
            else{
                head = curNode->next;
            } 
            free(curNode);
            printf("Employee %d removed from database", tempID);
            return;//assuming empId is unique return after you flound it.
        }
        prevNode = curNode;
        curNode = curNode->next;
    }
 }

最佳答案

我要在这里尝试一下,但可能是因为这个:

curNode = curNode->next;

因为当它删除所有内容时,它会寻找一个不存在的节点。所以我建议你改变

while (curNode != NULL)

while (curNode -> next != NULL)

希望这有帮助!

关于c - 删除列表中唯一的值后显示列表时出现错误处理中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29925917/

相关文章:

c - 结构声明中是否允许额外的分号?

c - 有没有办法在 printf 中不指定说明符?

java - 如何在 JNI 中将 Java 长对象传递给 C

loops - 在单链接列表中检测循环的开始?

Java链表lastIndexOf不工作

c++ - 如何在两个 boost::intrusive::slist 对象之间传输节点

char 和 printf 打印乱码

c - C编程的良好礼仪

c - 为什么这个 MEXed C/magma 代码会出现段错误,而独立的 C 代码可以工作?

c - 将数组作为参数传递给函数而不将数组的长度传递给该函数