0

It must be the way my professor declared the typedefs, because I haven't run into this problem yet.

I have the following (piece) of a header file, and the accompanying code that uses it:

polynomial.h -

#ifndef POLYNOMIAL_H_
#define POLYNOMIAL_H_

struct term {
    int coef;
    int exp;
    struct term  *next;
};

typedef struct term term;

typedef term * polynomial;

#endif

polynomial.c -

#include "polynomial.h"

void display(polynomial p)
{

    if (p == NULL) printf("There are no terms in the polynomial...");

    while (p != NULL) {

        // Print the term
        if (p.exp > 1) printf(abs(p.coef) + "x^" + p.exp);
        else if (p.exp == 1) printf(abs(p.coef) + "x");
        else printf(p.coef);

        // Print the sign of the next term, if it applies
        if (p.next != NULL) {
            if (p.next->coef > 0) printf(" + ");
            else printf(" - ");
        }
    }
}

But I get the following for every time I try to access any property of the struct:

error: request for member 'exp' in something not a structure or union

The includes, definitions and all that are there -- I just did something similar in C with structs and typedefs, but I didn't use this syntax: typedef term * polynomial;. I guess this might be causing the problem, and throwing me off.

If I can't access the members of the struct as p.exp, p.coef, and p.next, how can I?

PS - Exactly what does typedef term * polynomial; do/mean? I imagine that "multiple terms make up a single polynomial" but I don't understand how access to terms changes.

Chris Cirefice
  • 5,475
  • 7
  • 45
  • 75
  • You clearly defined your `polynomial` as a pointer type. So, `p` is a pointer. Why aren't you using it as a pointer? The compiler is telling you that operator `.` cannot be used with pointers. – AnT stands with Russia Oct 06 '13 at 17:37
  • Yeah I see that now. The spacing just confused me. In my code, I always keep the asterisk and variable names together instead of spaced out, because otherwise it looks like multiplication, and because of years of math I don't even think of an asterisk as anything else except that. I just glanced over that aspect of it is all. I understand the need to dereference, I just didn't even notice the pointer in the `polynomial typedef` =/ – Chris Cirefice Oct 06 '13 at 17:42

1 Answers1

1

polynomial is typedefed as a pointer to term. You cannot use . to access its elements. You have to either dereference it first:

(*p).next

or use arrow operator:

p->next
danadam
  • 3,350
  • 20
  • 18
  • I will accept this answer soon, when SO lets me! Anyway, that makes sense. It looked to me, the way he defined `typedef term * polynomial;`, that it was *term (times) term = polynomial*, not *term(star) is a polynomial - a pointer to a term*. I should pay more attention to how spaces can be used... it just looked really confusing so I didn't recognize it. New to C! :) – Chris Cirefice Oct 06 '13 at 17:40