-
Linked List headaches
okay, I'm writing a program that manipulates polynomials. the input looks like this: 2x3+3x2+4x+1
right now I'm working on the input and output functions. so far I've been able to successfully input one term of the polynomial, but for some reason I can't output it. here's what my code looks like:
Code:
//struct that holds one term (i.e. 2x3) in a polynomial
struct term
{
int co; //coefficient
int exp; //exponent
term* link;
};
typedef term* termptr;
//class that uses a linked list to hold a polynomial
class Polynomial
{
public:
Polynomial() {head = NULL;}
termptr get_head() {return head;}
void set_head (termptr t1);
friend istream& operator >> (istream& ins, Polynomial p1);
friend ostream& operator << (ostream& outs, Polynomial p1);
private:
termptr head;
};
//set function for head. I'm not really sure if this is right
void Polynomial::set_head (termptr t1)
{
head = t1;
}
//input operator overload for Polynomial class
istream& operator >> (istream& ins, Polynomial p1)
{
char x, sign;
termptr new_term;
new_term = new term;
new_term->link = NULL;
ins >> new_term->co >> x >> new_term->exp;
ins.ignore();
p1.set_head(new_term);
return ins;
}
//output operator overload for Polynomial
ostream& operator << (ostream& outs, Polynomial p1)
{
termptr ptr;
ptr = p1.get_head();
outs.setf(ios::showpos);
outs << ptr->co;
outs.unsetf(ios::showpos);
outs << "x" << ptr->exp;
return outs;
}
//main file
int main()
{
Polynomial poly1;
cout << "Please enter a term: ";
cin >> poly1;
cout << endl << poly1;
return 0;
}
I didn't put include or using statements in this because those are all right, I'm getting no syntax errors. right now I'm just trying to get it to work for one term. I keep getting a segmentation fault when I run the program
-
Hi,
Your problem is here:
istream& operator >> (istream& ins, Polynomial p1)
When you do this:
cin >> poly1;
poly1 is 'passed by value', which means the function makes a copy of it. Inside the function, all the values are diligently set for the copy, and then when the function returns, the copy is destroyed. The net effect is that your function doesn't do anything. Notably, poly1 is left unchanged and it remains a null pointer. Subsequently, when you do this:
cout << endl << poly1;
your <<operator function tries to dereference a null pointer.
-
ah, thank you very much. I knew it was something simple like that
-
By the way, I think typedef'ing in order to hide simple pointer notation is a horrible idea, and it's probably what led to your error.