【问题标题】:I get a segmentation fault when implementing a append function for a linked list为链表实现附加功能时出现分段错误
【发布时间】:2014-02-03 21:31:21
【问题描述】:

我将 head 定义为全局变量。用户输入应附加到单链表的整数。我实现了附加功能,但它给了我一个分段错误。

void Append(int x)
{
    struct Node *temp, *current;
    temp = (struct Node*)malloc(sizeof(struct Node));
    temp -> data = x;


    temp -> next = NULL;

    if(head->next ==NULL)
    {
            head = temp;

    }
    else{

            //current = (struct Node*)malloc(sizeof(struct Node));
            current = head;
            while(1)//current != NULL)
            {
                    if(current->next ==NULL)
                    {
                            current =current -> next;
                            printf("added to the end\n");
                            break;
                    }

                    current = current -> next;
            }
    }
}

主要功能如下:

int main()
{
    //create empty List
    head =NULL;

    printf("How many numbers?\n");
    int n,i,x;
    scanf("%d",&n);
    for(i =0; i<n; i++)
    {

            printf("Enter the number\n");
            scanf("%d",&x);
            //Insert(x);
            Append(x);
            Print();
    }
    return 0;
} 

【问题讨论】:

  • 并更改为if(current-&gt;next ==NULL){current -&gt; next = temp,;

标签: c linked-list segmentation-fault


【解决方案1】:

你将 head 设置为 null

head =NULL;

下次访问它时,您会尝试访问它的一个属性

if(head->next ==NULL)

你不能这样做,因为没有head-&gt;next 因为head 是空的

【讨论】:

    【解决方案2】:

    由于您将head 初始化为NULL,因此此行会导致错误:

    if(head->next ==NULL)
    

    当您尝试访问 NULL 指针的成员 next 时。

    要解决此问题,请在调用 Append 之前分配 head,或检查 head 是否在 NULLAppend

    【讨论】:

      【解决方案3】:

      //Insert(x);=> 启用此功能并更新有效的头节点。如果不在 Append() 函数中,则 if(head->next) 应更改为 if(head)。那就是在访问下一个之前必须验证头指针..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-30
        • 1970-01-01
        • 2022-10-19
        • 2021-01-17
        • 2015-05-28
        相关资源
        最近更新 更多