C编程分段故障链表程序

标签 c pointers linked-list segmentation-fault

我对 c(和这个网站)相当陌生,并且遇到了很多段错误问题。我正在编写一个程序,该程序创建一个数字链接列表并按升序插入值。

     void insert(struct element **head, struct element *new){   
            if((*head)->next == NULL && (*new).i > (*(*head)->next).i){
                (*head)->next = new;
                return;     
            }
            if((*head)->next == NULL && (*new).i < (*(*head)->next).i){
                new->next = (*head)->next;
                *head = new;    
                return;
            }
            struct element *prev = *head;
            struct element *current = (*head)->next;
            while(current->next != NULL){
                if((*new).i < (*current).i){
                    prev = current;
                    current = current->next;
                } else if((*new).i > (*current).i){
                    new->next = current;
                    prev->next = new;
                }
            }
        }
        int main (void){
            struct element **head;
            int value;
            printf("%s", "TEST" );
            printf("%s" , "Please type in an integer value. ");
            scanf("%d" , &value);
            printf("%s", "TEST" );
            do{
                printf("%s", "TEST" );
                struct element *new;
                if((new = malloc(sizeof(struct element))) == NULL){
                return(NULL);
                }
                printf("%s", "TEST" );
                (*new).i = value;
                printf("%s", "TEST" );
                if(head == NULL){
                    *head = new;
                    printList(*head);
                }  else if(value <= 0){
                    printListBackwards(*head);
                }   
                else {

                    insert(head, new);
                    printList(*head);
                }
                } while(value > 0);

我不需要关于插入或其他逻辑是否正确的帮助。我什至没有机会真正测试它,因为在提示后输入整数后,我立即得到段错误。我知道这看起来很时髦,但规范要求您使用指向结构体(链表的头)的指针。

最佳答案

您确定希望 head 成为 element** 而不是 element* 吗?这种额外的分离程度会给您带来问题,其中最重要的是代码非常难以阅读。

这是我最关心的事情:

if(head == NULL){
    *head = new;
    printList(*head);
}

您确认 head 是 NULL 指针,然后立即尝试使用 * 取消引用它。如果你真的坚持 head 是一个双指针,那么你需要在取消引用它之前动态分配它。就像这样:

if(head == NULL){
    head = malloc(sizeof(element*));
    *head = new;
    printList(*head);
}

这实际上在语法上可能并不完美(我来自 C++),但你明白了。但说到 C++,在 C 中将变量命名为“new”通常被认为是不好的做法,因为 new 是 C++ 中的关键字。

关于C编程分段故障链表程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824554/

相关文章:

c - 如何避免双重释放或损坏 (!prev)

c++ - 如何从 C 调用用 C++ 编写的库?

C++ 重载 : overload of operator =

c - 这些声明之间的技术差异是什么?

c - qsort 指向链表的指针数组,按结构成员值

c++ - 使用递归从尾部开始反转链表

c - 如何在nginx源码中加入Shared libraries进行编译?

c - 文件读/写缓冲区的最佳类型

c - 使用指针的指针来引用矩阵

c++ - 确定链表中的第一个节点