一、实验目的
巩固线性表的数据结构的存储方法和相关操作,学会针对具体应用,使用线性表的相关知识来解决具体问题。
二、实验内容
建立一个有n个学生成绩的线性表,n的大小由自己确定,用间接寻址实现数据的对表进行插入、删除、查找等操作。分别输出结果。
三、算法实现
#include
using namespace std;
const int MAX_SIZE=100;
struct node{
float score;
};
class Score_indirect{
private:
node *score[MAX_SIZE];
int length;
public:
Score_indirect();
Score_indirect(float a[],int n);
~Score_indirect();
float getValue(int index);
void locate(float x);
void insert(int index,float x);
float _delete(int index);
void print();
};
Score_indirect::Score_indirect(){
for(int i=0;i
MAX_SIZE) throw"参数非法!\n\n";
for(int i=0;i
score=a[j];
}
length=n;
}
Score_indirect::~Score_indirect(){
int i=0;
node *p;
while(i++
length) throw"查找位置非法!\n\n";
return score[index-1]->score;
}
void Score_indirect::locate(float x){
if(length==0) throw"成绩为空!\n\n";
bool b=false;
for(int i=0;i
score==x){ cout<
<<" "; b=true; } } if(!b) cout<<"没有该成绩!\n\n"; } void Score_indirect::insert(int index,float x){ if(index<1||index>length+1) throw"插入位置非法!\n\n"; for(int i=length;i>index-1;i--){ score[i]=score[i-1]; } score[index-1]=new node; score[index-1]->score=x; length++; } float Score_indirect::_delete(int index){ if(length==0) throw"成绩为空!\n\n"; if(index<1||index>length) throw"删除位置非法!\n\n"; node *p=score[index-1]; float x=p->score; for(int i=index-1;i
score<<" "; } cout<
<
四、运行结果
异常调试:
五、异常分析
出现这种错误的原因:
①可能存在野指针;
②内存泄露。。。
该程序解决方法:
①使用Win32 Release编译(组建->配置->移除Win32 Debug);
②给指针数组分配空间时,给每个指针赋值NULL;
指针所指的内存被释放时,给指针赋值NULL。
六、野指针
>野指针是指向被释放的或者未申请访问受限内存区域的指针。
>原因:
①指针变量未初始化:缺省值是随机的,会乱指一气
②指针释放后未置空:指针指向“垃圾”内存
③指针操作超越变量作用域:如栈内存在函数结束时会被释放