我的代码在插入函数(分段错误)时崩溃,它看起来像'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;}
您将此标记为C++,但这是一种非C++方法。您使用的唯一一个C++特定的东西是'std :: cout' :) – dreamlax
太多的缺陷......无论是在代码中,还是编码风格... – alphacentauri