【发布时间】:2014-05-19 21:49:57
【问题描述】:
我正在尝试创建一个链接列表,然后将节点值回显到控制台。但是使用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;
}
【问题讨论】:
-
一个简单的调试会话会告诉您,在调用 createList 之后“start”的值没有改变。那么你会问一个更集中的问题,例如“为什么 createList 返回时不开始更改值?”
-
哦。是的。我会从下次开始做。 :)
标签: c++ data-structures linked-list segmentation-fault