【发布时间】:2014-07-03 20:18:41
【问题描述】:
我在编译这段代码时遇到了分段错误,我相信它是由这里的这个块引起的。
EmployPtr iter;
//Deletes nodes outside of range.
while(netSalary(iter)<45000 || netSalary(iter)>60000)
{
EmployPtr nodeToDelete = iter;
iter = iter->link;
delete nodeToDelete;
}
我发现指针非常令人困惑,并且有一个指针未指向内存中的有效对象,但我不确定如何解释它。我知道我需要在删除对象之前将对象的“下一个”(或“链接”我在代码中如何命名)指针重新分配给下一个指针,在对象被删除之后。我试图用代码做到这一点,但我仍然遇到段错误。谁能向我解释发生了什么并帮助我了解如何解决这个问题?
EmployPtr nodeToDelete = iter->link;
iter->link = nodeToDelete->link;
delete nodeToDelete;
[包括其余代码,以防需要引用。]
#include <fstream>
#include <iostream>
using namespace std;
struct Employee
{
string firstN;
string lastN;
float salary;
float bonus;
float deduction;
Employee *link;
};
typedef Employee* EmployPtr;
void insertAtHead( EmployPtr&, string, string, float, float,float );
void insert( EmployPtr&, string, string, float, float,float );
float netSalary( EmployPtr& );
int main()
{
//Open file
fstream in( "payroll.txt", ios::in );
//Read lines
string first, last;
float salary, bonus, deduction;
EmployPtr head = new Employee;
//Inserts all the data into a new node in the linked list, creating a new node each time the loop executes.
while( in >> first >> last >> salary >> bonus >> deduction)
insert (head, first, last, salary, bonus, deduction);
//Close file
in.close();
cout << "\t\t\t\t-Salary in the range of ($45,000 - $60,000)-\n" << "Printed in format: First Name, Last Name, Salary, Bonus, Deduction, Net Salary.\n\n";
//Deletes all nodes in the list that are not between 45,000 and 65,000. It then prints the newly modified list.
EmployPtr iter;
for(iter = head; iter!= NULL; iter = iter->link)
{
//Deletes nodes outside of range.
while(netSalary(iter)<45000 || netSalary(iter)>60000)
{
EmployPtr nodeToDelete = iter;
iter = iter->link;
delete nodeToDelete;
}
//Prints list.
cout << iter->firstN << ", " << iter->lastN << ", " << iter->salary << ", " << iter->bonus << ", " << iter->deduction << ", " << netSalary(iter) <<endl;
}
return 0;
}
void insertAtHead(EmployPtr& head, string firstValue, string lastValue,
float salaryValue, float bonusValue,float deductionValue)
{
//method definition
}
void insert(EmployPtr& afterNode, string firstValue, string lastValue,
float salaryValue, float bonusValue,float deductionValue)
{
//method definition
}
float netSalary(EmployPtr& node)
{
//method definition
}
[更新代码]
//Deletes nodes outside of range.
while((netSalary(head)<45000 || netSalary(head)>60000) && head!=NULL)
{
EmployPtr nodeToDelete = head;
head = head->link;
delete nodeToDelete;
nodeToDelete->link = head;
}
//Prints List
EmployPtr iter;
for(iter = head; iter!= NULL; iter = iter->link)
{
cout << iter->firstN << ", " << iter->lastN << ", " << iter->salary << ", " << iter->bonus << ", " << iter->deduction << ", " << netSalary(iter) <<endl;
}
【问题讨论】:
-
如果您发现指针令人困惑,那么 1. 切换到托管语言,2. 或至少使用
std::list。 -
很遗憾,这对我来说不是一个选择,而且我的指导方针规定我必须实施我自己的列表,所以这也不是一个选择。
-
编译时出现分段错误?真的 ??编译器真的会给出分段错误吗?
标签: c++ pointers segmentation-fault