c - 尝试将节点插入链表时出现段错误

标签 c list insert segmentation-fault

我几天前通过《C 编程》这本书开始学习 C 编程,并且我有 java 的先验知识。将节点插入链表在 java 中非常容易,但我想我是否可以在 C 中做同样的事情。 所以,我想出了这个程序,

#include "node.h"

void insertEntry(struct node* root, struct node* after)
{
    struct node* first = root;
    while(first != (struct node*) 0)
    {
        if(first->value == after->value)
        {
            struct node ins;
            ins.value = 3456;
            ins.next = first->next;
            first->next = &ins;
        }
        first = first->next;
    }
}

int main(void)
{
    struct node n1, n2, n3;
    struct node* list_pointer = &n1;

    n1.value = 100;
    n1.next = &n2;

    n2.value = 200;
    n2.next = &n3;

    n3.value = 300;
    n3.next = (struct node*) 0;

    void insertEntry(struct node* root, struct node* after);

    while (list_pointer != (struct node*) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }
    printf("\n");

    list_pointer = &n1;

    insertEntry(list_pointer, &n2);

    while (list_pointer != (struct node*) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }

    return 0;
}

节点.h

#include <stdio.h>

struct node
{
    int value;
    struct node* next;
};

基本上,这个程序获取指向链表第一个元素的指针和指向要插入的元素的指针,并在该节点之后插入一个新节点。

但是当我运行这个程序时,我的程序崩溃了,我无法找到这个错误发生的位置和原因。 我查看了 Java 中的代码并尝试在 C 中实现相同的代码。

谢谢。

最佳答案

这是你的问题:

    {
        struct node ins;  // You create an object in the stack
        ins.value = 3456;
        ins.next = first->next;
        first->next = &ins;   // You reference your object
    }  // Your object is popped out of the stack and ceases to exist
    // Any access to first->next past this block may cause segfault

为了避免这种情况,您可以使用 malloc() 创建 ins,但要注意:这不是 java,您必须跟踪所有对象自己在堆中分配。

关于c - 尝试将节点插入链表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31272589/

相关文章:

c# - 如何在 C# 中使用列表创建循环

C++ Map无法插入对

REGEX:在之前、之后或之间插入的最佳实践?

c - 在 C 中实现二进制搜索

c - 32 位和 64 位机器中的位操作

php - $_GLOBAL 、 $_POST 等全局变量存储在哪里?

python - 如何按范围对列表元素进行分组/计数

list - 使用过滤器迭代列表

C 设计模式在不阻塞的情况下执行操作列表?

php - MySQL:向表中插入多行数据,一些数据来自另一个表(关系型)