首页 > 解决方案 > 链表 C 中的分段错误

问题描述

下面是我的程序,我尝试了几种方法,但我无法得出结论,因此卡住了,有人可以帮忙吗?

有什么问题和任何替代方法?

struct Node
    {
        int data;
        struct Node *prev,*next;
    };

插入元素

   void push(struct Node *start,struct Node *end,int x,int loc)
    {
        struct Node *new=(struct Node*)malloc(sizeof(struct Node));
        new->data=x;
        if(start==NULL)
        {
            new->next=NULL;
            new->prev=NULL;
            start=new;
            end=new;

        }
        else 
        {
            if(loc==1)
            {
                new->prev=NULL;
                new->next=start;
                start->prev=new;
                start=new;
            }
            else
            {
                struct Node *ptr=start;
                for(int i=0;i<loc-1;i++)
                {
                    ptr=ptr->next;
                }
                if(ptr->next==NULL)
                {
                    new->next=NULL;
                    new->prev=ptr;
                    ptr->next=new;
                    end=new;
                }
                else
                {
                    new->next=ptr->next;
                    new->prev=ptr;
                    ptr->next->prev=new;
                    ptr->next=new;
                }
            }
        }
    }

从头开始显示

void display_start(struct Node *temp)
        {
            struct Node *ptr=NULL;
            for(ptr=temp;ptr->next!=NULL;ptr=ptr->next)
            {
                printf("%d\t",ptr->data);
            }
           printf("%d",ptr->data);
        }

从末端显示

        void display_end(struct Node *temp2)
        {
            struct Node *ptr=NULL;
            for(ptr=temp2;ptr->prev!=NULL;ptr=ptr->prev)
            {
                printf("%d\t",ptr->data);
            }
            printf("%d",ptr->data);
        }

主功能

        int main(void) {
            // your code goes here
        struct Node* head=NULL;
        struct Node* tail=NULL;

        push(head,tail,1,1);
        push(head,tail,2,2);
        push(head,tail,3,2);
        push(head,tail,4,3);
        push(head,tail,5,5);
        push(head,tail,6,4);

        printf("From Start: ");
        display_start(head);
        printf("From End: ");
        display_end(tail);
            return 0;
        }

一个编译器显示垃圾值,另一个显示分段错误

据我所知,显示列表时出现错误。

标签: clinked-list

解决方案


display_start()不打印列表的 一个可能原因是,您传递了在 C 中被视为按值调用的headto函数。因此,您在函数中进行的任何修改都不会在函数中受到影响,并且列表仍然为空。push()headpush()main()

不只是传递headpush()函数,而是传递 的地址head,同样适用于tail也。

例如

push(&head,&tail,1,1);

并做相应的push()功能变化。

void push(struct Node **start,struct Node **end,int x,int loc) {

/* Do changes here */

}

-Wall还要用类似标志编译你的程序,gcc -Wall test.c不要忽略警告,解决它们。通过编译更好地将所有警告视为错误,-Wstrict-prototypes -Werror以便减少错误的机会。例如

gcc -Wall -Wstrict-prototypes -Werror test.c

最后学习如何调试小代码https://ericlippert.com/2014/03/05/how-to-debug-small-programs/


推荐阅读