【发布时间】:2017-03-18 06:25:00
【问题描述】:
我已经在这工作了 4.5 个小时,试图弄清楚为什么这不起作用。仍然没有运气。我不断收到分段错误,或者尽管构建成功,但列表永远不会显示。
SimpleVector.h
// SimpleVector class template
#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <iomanip>
using namespace std;
class SimpleVector
{
private:
struct Link{
int data;
Link *next;
};
Link *head;
public:
// Default constructor
SimpleVector()
{head = NULL;}
// Destructor declaration
~SimpleVector();
void linkList(int);
//void insertLink(T);
void displayList();
};
//Destructor for SimpleVector
SimpleVector::~SimpleVector(){
Link *linkPtr;
Link *nextPtr;
nextPtr = head;
while(linkPtr != NULL){
nextPtr = linkPtr->next;
}
delete linkPtr;
linkPtr = nextPtr;
}
//Creation of List
void SimpleVector::linkList(int size){
Link *newLink = new Link; //create first link
head = newLink; //
head->data = size--; //Fill the front with data
head->next = NULL; //Point the front to no where
do{
Link *end = new Link; //Create a new link
end->data = size--; //Fill with data
end->next = NULL; //Point to no where
head->next = end; //Previous link will point to the end
// head = end; //Move to the end
}while(size > 0); //Repeat until filled
}
//Creation of Link and insertion
/*
template <class T>
void SimpleVector<T>::insertLink(T){
}
*/
//Function to print the entire list
void SimpleVector::displayList(){
Link *linkPtr;
linkPtr = head;
while(linkPtr != NULL){
cout<<setprecision(3)<<linkPtr->data;
linkPtr = linkPtr->next;
}
}
#endif
main.cpp
// This program demonstrates the SimpleVector template.
#include <iostream>
#include "SimpleVector.h"
using namespace std;
int main(){
int SIZE = 10; // Number of elements
// Create a SimpleVector of ints.
SimpleVector intTable;
intTable.linkList(SIZE);
intTable.displayList();
return 0;
}
【问题讨论】:
-
尽管构建成功 -- 成功构建仅意味着您的程序中没有语法错误。它与逻辑是否正确或您的程序是否会产生正确的结果无关。
-
哪一行产生分段错误?
-
你的析构函数是错误的,因为它使用了未初始化的局部变量。你的编译器没有警告你这个?
-
@PaulMcKenzie 不,它没有
-
@EggplantMachina -- 你声明了
linkPtr,从不将其设置为任何值,然后在while循环中使用它。因此,您使用的是未初始化的指针。
标签: c++ linked-list segmentation-fault