簡體   English   中英

在C中實現鏈表時出現分段錯誤

[英]Segmentation fault while implementing linked list in C

我正在嘗試創建一個簡單的鏈接列表,並在列表末尾插入一個節點。 我遇到了細分錯誤。

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node *link;
};

void create(struct node *head){
    struct node* second = NULL;
    struct node* last = NULL;

    second = (struct node*)malloc(sizeof(struct node));
    last = (struct node*)malloc(sizeof(struct node));

    second -> data = 2;
    last -> data = 3;

    head -> link = second;
    second -> link = last;
    last -> link = NULL;
}

void insert_ending(struct node *head){
    struct node* temp = NULL;
    struct node* temp1 = NULL;

    temp1 = (struct node*)malloc(sizeof(struct node));
    temp1 -> data = 5;
    temp1 -> link = NULL;

    temp = head;
    while(temp != NULL){
       temp = temp -> link;
    }temp -> link = temp1;
}

void PrintList(struct node *head){
    while( head != NULL ){
        printf(" %d -->", head -> data);
        head = head -> link;
    }
    printf("\n");
}

int main(){
    struct node* head = NULL;
    head = (struct node*)malloc(sizeof(struct node));
    head -> data = 1;
    head -> link = NULL;

    create(head);
    PrintList(head);

    insert_ending(head);
    PrintList(head);
    return 0;
}

我遇到了細分錯誤。 輸出如下。

1-> 2-> 3->分段錯誤(核心已轉儲)

在插入函數中,您需要更改為:

 temp = head;
    while(temp -> link != NULL){
       temp = temp -> link;
    }
    temp -> link = temp1;

原因是,當您使用while循環直到temp == null時,您之后不能再執行:temp-> link,因為temp都已為null。

在while循環中的函數“ insert_ending”中,您希望將條件更改為:

while ( temp != NULL ) 

至:

while ( temp->link != NULL )

因為現在循環完成后,temp為NULL,然后嘗試取消引用它(一個NULL指針)並得到一個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM