通过将某人排序到链表中来添加某人时出现分段错误的原因
The reasons for segmentation fault while adding someone by sorting them into the linked list
列表项
void MovieDatabase:: addActor(const string movieTitle, const string actorFirstName, const string actorLastName, const string actorRole ){
bool found = false;
Movie* temp;
for(Movie* m= headMovie; m != NULL; m = m-> next){
if(m-> title == movieTitle){
found = true;
temp = m;
break;
}
}
if(found){
if(headCast == NULL)
headCast = new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
else{
Cast *c = new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
Cast *temp = headCast;
for(Cast* cur = headCast; cur -> next != NULL; cur = cur -> next){
if(cur ->next -> lastName < actorLastName){
temp = temp -> next;
}
else{
c -> next = cur -> next;
temp -> next= c;
break;
}
}
}
}
else
cout << "The movie with a " << movieTitle << " does not exist in the database,you can not add the actor. " << endl;
size++;
}
大家好,我编辑了代码,现在我不承担任何责任。但是,它不显示任何输出。这意味着它不添加任何东西。在任何情况下,我都要发送用于显示的代码。
void MovieDatabase:: showActors(){
for(Cast * cur= headCast; cur != NULL; cur = cur -> next){
cout << cur -> lastName << endl;
}
}
在这段代码中:
for(Cast* cur = headCast; cur != NULL; cur = cur -> next){
if(cur ->next -> lastName < actorLastName){
您只检查cur != NULL
,然后解除对cur->next
的引用。cur->next
可能为NULL
temp
和cur
似乎都指向同一个节点。也许您打算将其中一个放在另一个的前面,以便您有指向前一个节点的指针进行插入?
这是一个(未经测试的)实现:
Cast *c = new Cast(actorFirstName, actorLastName, actorRole, movieTitle);
Cast *prev = NULL; // maintain a pointer to the previous node. No previous node initially.
Cast *cur;
for(cur = headCast; cur != NULL; cur = cur -> next)
{
if(cur -> lastName > actorLastName) break; // stop if we find a place to insert.
prev = cur; // update previous pointer before looping.
}
if(prev != NULL)
{
prev -> next = c; // if there is a previous node, use 'c' as its next node.
} else {
headCast = c; // otherwise 'c' is the new head node.
}
c -> next = cur; // the 'current' node always goes after 'c'.
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 在线编译器中的分段C++没有打印消息
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 通过将某人排序到链表中来添加某人时出现分段错误的原因