簡體   English   中英

如何在單鏈表(C)中正確添加一個int?

[英]How do I correctly prepend an int in a singly linked list (C)?

我在.c文件中定義了此結構:

typedef struct node
{
    // the value to store in this node
    int i;

    // the link to the next node in the list
    struct node* next;
}
node;

我編寫了一個prepend函數,可以在main的for循環中使用它來測試一些值:

void prepend(int i)
{
    node* newNode = NULL;
    if(first->next == NULL)
    {
        newNode->i = i;
        first->next = newNode;
        newNode->next = NULL;
    }
    else
    {
        newNode->next = first->next;
        newNode->i = i;
        first->next = newNode;      
    }
}

我究竟做錯了什么? 運行程序時出現分段錯誤。

編輯:程序到達if(first-> next == NULL)時出現錯誤

該代碼在if/else兩個分支中都取消引用了稱為newNodeNULL指針。 取消引用NULL指針是未定義的行為,在這種情況下是分段錯誤。 在使用內存之前,使用malloc()newNode分配內存:

node* newNode = malloc(sizeof(*newNode));
if (newNode)
{
    newNode->i = i; /* No need to repeat this in both branches. */
    /* ... snip ... */
}

使用它之前, first還必須指向一個有效node 請記住,當不再需要malloc()時, malloc()free()

暫無
暫無

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

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