0

Ich kann den Grund für den Segmentierungsfehler nicht finden. Ich würde Ihre Hilfe in jeder Hinsicht sehr schätzen. Danke im Voraus.Verknüpfte Liste mit Klassen- und Freundesfunktionen: Segmentierungsfehler

/Eine rudimentäre verkettete Liste zur Implementierung von Polynomen. Diese ist nur ein Experiment, da ich keine Erfahrung mit verknüpften Listen haben/

#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; 
} 

Dies ist die Ausgabe:

Geben Sie den Index und Koeff des Polynoms:

Segmentierungsfehler (Core Dumped)

Es akzeptiert nur ein Element (Index) und endet.

Antwort

1

Sie übergeben einen nicht initialisierten Zeiger. Sie müssen einige Speicher entweder mit neuen erwerben oder sie auf den Stapel gelegt:

Heap:

linked_list *obj1 = new linked_list; 

Stack:

linked_list obj1; 
garbage=start(&obj1); 
+0

Das funktionierte. Die erste Option meine ich. Vielen Dank!!! –