#c #pointers #linked-list
#c #указатели #связанный список
Вопрос:
Когда я работал над связанным списком в программе, он добавляет два многочлена, используя связанный список, и когда я скомпилировал его на своем ноутбуке, он напечатал бесконечный цикл, но онлайн-компиляция показала ошибку сегментации, я проверил все указатели, но я не смог это выяснить, можете ли вы помочь мне с этим? мои входные полиномы:
-многочлен 1 = x ^ 8 5x ^ 4 -7x ^ 2 6x
-многочлен 2= x^ 9 7x ^5 -3x^4 2x^3
- программа create_list создает список
- программа вставки вставляет узел в заданную позицию
- add_polynomials prog. добавляет два многочлена
struct node {
float cofficient;
int exponent;
struct node *next;
};
struct node *create_list()
{
struct node *head,*newnode,*temp;
printf("enter the number of terms:n");
int n;
scanf("%d",amp;n);
if(n==0){
printf("creating empty listn");
struct node *head=NULL;
return head;
}
int i=1;
newnode=(struct node *)malloc(sizeof(struct node));
printf("enter the cofficient and expression of term %d:n",i);
scanf("%f%d",amp;newnode->cofficient,amp;newnode->exponent);
newnode->next=NULL;
head=newnode;
temp=head;
for(i=2;i<=n;i ){
newnode=(struct node *)malloc(sizeof(struct node));
printf("enter the cofficient and expression of term %d:n",i);
scanf("%f%d",amp;newnode->cofficient,amp;newnode->exponent);
newnode->next=NULL;
temp->next=newnode;
temp=newnode;
}
return head;
}
void display(struct node *start)
{
if(start==NULL){
printf("nothing to displayn");
}
struct node *p=start;
int i=1;
while(p != NULL){
//printf("for term %d:n",i );
printf("%.1fx^(%d) ",p->cofficient,p->exponent);
if(p->next->cofficient >0)
printf(" ");
p=p->next;
}
}
struct node *insert(struct node *start,float coff,int expo)
{
struct node *newnode=(struct node *)malloc(sizeof(struct node ));
newnode->cofficient=coff;
newnode->exponent=expo;
newnode->next=NULL;
if(start ==NULL){
printf("inserting in the empty list...n");
start=newnode;
return start;
}
if(newnode->exponent > start->exponent){
newnode->next=start;
start=newnode;
return start;
}
struct node *temp,*p=start;
while(p->next != NULL){
temp=p->next;
if(temp->exponent <= newnode->exponent){
p->next=newnode;
newnode->next=temp;
return start;
}
p=p->next;
}
if(newnode->exponent < p->exponent){
p->next=newnode;
newnode->next=NULL;
return start;
}
}
struct node *add_polynomials(struct node *start1,struct node *start2)
{
struct node *p1,*p2;
p1=start1;
p2=start2;
//struct node *newnode;
struct node *p3_start=(struct node *)malloc(sizeof(struct node ));
//p3_start=NULL;
while(p1 != NULL amp;amp; p2 != NULL){
if(p1->exponent > p2->exponent){
p3_start=insert(p3_start,p1->cofficient,p1->exponent);
p1=p1->next;
//continue;
}
else if(p1->exponent < p2->exponent){
p3_start=insert(p3_start,p2->cofficient,p2->exponent);
p2=p2->next;
//continue;
}
else if(p1->exponent == p2->exponent){
p3_start=insert(p3_start,p1->cofficient p2->cofficient,p1->exponent);
p1=p1->next;
p2=p2->next;
}
}
while(p1 != NULL){
p3_start=insert(p3_start,p1->cofficient,p1->exponent);
p1=p1->next;
}
while(p2 != NULL){
p3_start=insert(p3_start,p2->cofficient,p2->exponent);
p2=p2->next;
}
return p3_start;
}
int main ()
{
struct node *p1_head,*p2_head,*p3_head;
p1_head=(struct node *)malloc(sizeof(struct node ));
p1_head=create_list();
p2_head=(struct node *)malloc(sizeof(struct node ));
p2_head=create_list();
p3_head=(struct node *)malloc(sizeof(struct node ));
p3_head=add_polynomials(p1_head,p2_head);
display(p3_head);
return 0;
}
Комментарии:
1. Запустите свой отладчик, выясните, какая строка выходит из строя, а затем включите эту информацию в свой вопрос.
2. Вы выполняли какую-либо отладку самостоятельно? Запустите свою программу в отладчике — как минимум, это даст вам точную строку кода, которая вызывает ошибку сегментации. Вы также можете использовать такие инструменты, как valgrind , чтобы помочь найти ошибки, связанные с памятью.
3. Существует много проблем. Прежде всего, вам нужно понять, что
p1_head=(struct node *)malloc(sizeof(struct node ));
заp1_head=create_list();
этим следует бессмысленно. Это так же, какa = 5;
следовать непосредственно заa = 42;
. Ваш код полон этих проблем. Также весь код очень запутанный.4. Каковы ваши входные данные в программу?
5. При запуске программы вы получаете вопросы: введите количество терминов: и так далее. Было бы проще протестировать, если вы предоставите свои входные значения.
Ответ №1:
При тестировании этого мне нужно было изменить отображение функций
if(p->next->cofficient >0)
printf(" ");
Для
if(p->next != NULL)
if(p->next->cofficient >0)
printf(" ");
В противном случае вы пытаетесь разыменовать указатель p-> next, который равен нулю.
Если вы узнаете, как запускать код в отладчике, эти типы ошибок легко найти.