2013-12-10 36 views
-2

我的代码在插入函数(分段错误)时崩溃,它看起来像'List.last'表现为静态但不是。不要介意代码的其余部分。我知道解决方案一定很简单,但它让我感到头疼。这是一个很长一段时间我学什么编码Seg Fault C++,list,list.last

#include <iostream> 
#include <string> 
#include <cmath> 
#include <iomanip> 
using namespace std; 

typedef int elementtype, position ; 
const int maxlength=10; 
struct List 
{ 
    elementtype elements[maxlength]; 
     elementtype last; 
}; 

position END(List l) 
{ 
return(l.last+1); 
} 

position First(List l) 
{ 
if (l.last>=0) 
return(l.last); 
else 
return(END(l)); 
} 

position Next(position p,List l) 
{ 
return(l.elements[p+1]); 
} 


position Previous(position p,List l) 
{ 
return(l.elements[p-1]); 
} 



position Locate(elementtype x, List l) 
{ int i; 
for(i=0;i<=maxlength;i++) 
{ 
if(x==l.elements[i]) 
return(i); 
else 
return(END(l)); 
} 
} 

elementtype Retrieve(position p, List l) 
{ 
return(l.elements[p]); 
} 

bool Insert(int x, position p, List &l) 
{ 
int i; 

if(l.last-1==maxlength) 
return(false); 
else 

if((p>=0)&&(p<=maxlength)) 
{l.last++; 
for(i=l.last;i>p;i--) 
l.elements[i+1]=l.elements[i]; 
l.elements[p]=x; 
return(true);} 
else return(false); 

    } 

bool Delete(position p, List &l) 
{ 
int i; 
if(p>0||p<l.last){ 
l.elements[i]=l.elements[i+1]; 
l.last=l.last-1; 
return(true);} 
else 
if(p=l.last){ 
l.last=l.last-1; 
return(true);} 
else 
return(false); 

} 

void print(List l) 
{ 
    position i=First(l); 
    while (i!=END(l)) 
    { 
     cout<< Retrieve(i,l); 
     i=Next(i,l); 
    } 
    cout<<("\n"); 

} 



int main(){ 
List l; 
l.last=-1; 
Insert(100,First(l),l); 
print (l); 
cout<<l.elements[0]; 
for (int i=0; i<3;i++) 
Insert(i,First(l),l); 
print (l); 

Insert (20,Previous(END(l),l) ,l); 
print(l); 
Delete(Locate(20,l),l); 
print(l); 
return 0;} 
+0

您将此标记为C++,但这是一种非C++方法。您使用的唯一一个C++特定的东西是'std :: cout' :) – dreamlax

+1

太多的缺陷......无论是在代码中,还是编码风格... – alphacentauri

回答

2

在这里,您Locate功能

for(i=0;i<=maxlength;i++) 

你有你的允许

长度10.更改的数组索引10的访问的问题
for(i=0;i<maxlength;i++) 

同样在这里Insert

if((p>=0)&&(p<=maxlength)) 

允许在这条线

l.elements[p]=x; 

当前访问超过数组元素的限制指数10的稍后访问。如果数组的大小为x,则不能访问array[x],因为索引是从零开始的。

使用调试器可以帮助您识别这一点。

+0

你确定它会使它工作吗?在'Insert'中引起'l.last ++'的注释使它工作并将它放在那里,甚至在主文件中递增它给了我seg。故障。 – user3086720

+0

@ user3086720不,我不确定 - 要完全确定的唯一方法就是在调试器中运行它 - 这就是你应该做的。我只强调了几个实例,其中循环变量的限制允许访问数组中的越界元素。 – mathematician1975

0

除了由@ mathematician1975建议的修改,一个基本的错误是在

print(List) 方法。

当语句i=Next(i,l);执行时,它从List.elements数组中获取一个值,该数组最初包含随机值。那么变量i中是什么是一个随机索引阵列似乎正在产生分段故障。