Search code examples
bisonflex-lexer

bison recursion error with struct pointer


I have a simple struct called Polyn like this:

typedef struct Polyn {
  int sign;
  int coeff;
  int exp;
  struct Polyn *next;
} Polyn;

In my bison grammar for recursively building polynomials I only get the first and last element. I use these functions to add and make terms with the Polyn struct:


Polyn *addmonomial(Polyn *pol, Polyn *monom) {
    pol -> next = monom;
    return pol; 
}

So for a=1x2+2x+3, it only gives me 1x2+3. The recursion will only build the first and last elements. I don't know whether to change the return value of the add function or how to change the grammar so the middle terms are included. It seems like the problem is $1 in my last two recursive rules is always the first term and doesn't become the middle terms. I need to return the first term for my other grammar rules but also build the polynomial.

    |poln T_PLUS poln   { $$ = addmonomial($1, $3);}
    |poln T_MINUS poln  { Polyn *p2n = negate($3); $$ = addmonomial($1, p2n); }

Solution

  • Polyn *addmonomial(Polyn *pol, Polyn *monom) {
        pol -> next = monom;
        return pol; 
    }
    

    This will override the existing value of next if pol already has a next value. So if pol represent the expression 1x2+2x and monom represents 3, then the 2x part will be overridden by 1.