使用 class 和友元函数的链表:分段错误
Linked list using class and friend functions: segmentation fault
我找不到分段错误的原因。非常感谢您以任何方式提供帮助。提前致谢。
/用于实现多项式的基本链表。
这只是一个实验,因为我没有使用链表的经验/
#include<iostream>
using namespace std;
class linked_list
{
//First element will hold index of the polynomial and the second element will hold its coefficient
int a[2];
linked_list *p;
public:
linked_list() //Constructor to initialize to zero
{
a[0]=0;
a[1]=0;
p=NULL;
}
friend int start(linked_list *obj1)
{
cout<<"Enter the index and coeff of the polynomial:\n";
cin>>obj1->a[0]; //Accepting the values of index and coeff
cin>>obj1->a[1];
linked_list *obj2;
int garbage; //A garbage just to hold the return value
char c;
cout<<"Enter y to continue or n to discontinue:\n";
cin>>c;
if(c=='y')
{
obj1->p=obj2; //Setting pointer of first node to point to the second
garbage=start(obj2);
return garbage;
}
else
{
obj1->p=NULL; //Setting last pointer to NULL
return 0;
}
}
friend void print(linked_list *obj1)
{
linked_list *temp; //Temporary object pointer
cout<<obj1->a[0]<<"x^"<<obj1->a[1];
temp=obj1;
while(temp->p!=NULL)
{
temp=temp->p; //Temporary object pointer now holds address of next location
cout<<"+"<<temp->a[0]<<"x^"<<temp->a[1];
}
}
};
int main()
{
int garbage;
linked_list *obj1;
garbage=start(obj1);
print(obj1);
return 0;
}
这是输出:
输入多项式的索引和系数:
0
分段错误(核心已转储)
它只接受一个元素(索引)并终止。
您正在传递一个未初始化的指针。您需要使用 new 获取一些内存或将其放入堆栈:
堆:
linked_list *obj1 = new linked_list;
堆栈:
linked_list obj1;
garbage=start(&obj1);
我找不到分段错误的原因。非常感谢您以任何方式提供帮助。提前致谢。
/用于实现多项式的基本链表。 这只是一个实验,因为我没有使用链表的经验/
#include<iostream>
using namespace std;
class linked_list
{
//First element will hold index of the polynomial and the second element will hold its coefficient
int a[2];
linked_list *p;
public:
linked_list() //Constructor to initialize to zero
{
a[0]=0;
a[1]=0;
p=NULL;
}
friend int start(linked_list *obj1)
{
cout<<"Enter the index and coeff of the polynomial:\n";
cin>>obj1->a[0]; //Accepting the values of index and coeff
cin>>obj1->a[1];
linked_list *obj2;
int garbage; //A garbage just to hold the return value
char c;
cout<<"Enter y to continue or n to discontinue:\n";
cin>>c;
if(c=='y')
{
obj1->p=obj2; //Setting pointer of first node to point to the second
garbage=start(obj2);
return garbage;
}
else
{
obj1->p=NULL; //Setting last pointer to NULL
return 0;
}
}
friend void print(linked_list *obj1)
{
linked_list *temp; //Temporary object pointer
cout<<obj1->a[0]<<"x^"<<obj1->a[1];
temp=obj1;
while(temp->p!=NULL)
{
temp=temp->p; //Temporary object pointer now holds address of next location
cout<<"+"<<temp->a[0]<<"x^"<<temp->a[1];
}
}
};
int main()
{
int garbage;
linked_list *obj1;
garbage=start(obj1);
print(obj1);
return 0;
}
这是输出:
输入多项式的索引和系数:
0
分段错误(核心已转储)
它只接受一个元素(索引)并终止。
您正在传递一个未初始化的指针。您需要使用 new 获取一些内存或将其放入堆栈:
堆:
linked_list *obj1 = new linked_list;
堆栈:
linked_list obj1;
garbage=start(&obj1);