如何在单链表(C)中正确添加int?

时间:2013-04-25 19:48:30

标签: 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;      
    }
}

我做错了什么?运行程序时出现Segmentation Fault。

编辑:我在程序到达if(first-> next == NULL)

时收到错误

1 个答案:

答案 0 :(得分:4)

代码在NULL的两个分支中取消引用newNode指针,称为if/else。取消引用NULL指针是未定义的行为,在这种情况下是分段错误。在使用之前使用malloc()newNode分配内存:

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

first在使用之前还必须指向有效的node。 <!{3}​​}当不再需要malloc()时,请记住free()