使用函数创建链表时出现分段错误

Segmentation fault when creating linked list with function

本文关键字:分段 错误 链表 函数 创建      更新时间:2023-10-16

>我正在尝试创建一个链表,然后将节点值回显到控制台。但是在main函数之外使用函数并调用它会导致segmentation fault(core dumped)。我想不通为什么。以下代码有效:

#include<iostream>
using std::cout;
using std::endl;
struct node
{
    int val;
    node* next;
};
void printList(node* start)
{
    node* temp; 
    temp = start;
    int i = 0;
    while(temp->next != NULL)
    {
        cout<<"The value in the "<<i<<"th node is : "<<temp->val<<endl;
        temp = temp->next;
        i++;
    }
}
int main() 
{
    node* start;
    node* temp;
    start = new node;
    temp = start;
    for(int i = 0; i < 10; i++)
    {
        temp->val = i*10;
        temp->next = new node;
        temp = temp->next;
    }
    temp->val = 0;
    temp->next = NULL;
    printList(start);
    return 0;
}

但这会引发分段错误

#include<iostream>
using std::cout;
using std::endl;
struct node
{
    int val;
    node* next;
};
void createList(node* start)
{
    node* temp;
    start = new node;
    temp = start;
    for(int i = 0; i < 10; i++)
    {
        temp->val = i*10;
        temp->next = new node;
        temp = temp->next;
    }
    temp->val = 0;
    temp->next = NULL;
}
void printList(node* start)
{
    node* temp; 
    temp = start;
    int i = 0;
    while(temp->next != NULL)
    {
        cout<<"The value in the "<<i<<"th node is : "<<temp->val<<endl;
        temp = temp->next;
        i++;
    }
}
int main() 
{
    node* start;
    createList(start);
    printList(start);
    return 0;
}

void createList(node* start)更改为void createList(node*& start) 。(见它工作)。

在C++中,除非另有说明,否则所有内容都按值传递。在本例中,您将传递指向节点 ( start ) 的指针以按值createList。您可以更改它指向的节点 ( start->... ),但不能更改指针本身,因为您正在使用副本。

通过引用传递指针允许您更改指针本身。

您将 start 参数传递到按值createList的函数中,这意味着当您这样做时

start = new node;

正在为start的副本分配新节点的地址。这意味着您在 main 中声明的 start 变量不会接收节点的地址。

若要解决此问题,请使用指针引用。通过引用(而不是按值)将start传递给createList。喜欢这个:

void createList(node*& start)

通过引用传递时,您将直接更改在 main 中声明的指针,而不是创建副本。