Cory
Cory

Reputation: 245

Dynamic Arrays and structs

Thanks! I just had to cast the right side of the assignment to Term.

I have to make a dynamic array of polynomials that each have a dynamic array of terms. When giving the term a exponent and coefficient, I get an error "expected expression before '{' token". What am I doing incorrectly when assigning the values?

Also, is there an easy way of keeping the dynamic array of terms ordered by their exponent? I was just planning on looping through, printing the max value but would prefer to store them in order.

Thanks!

polynomialArray[index].polynomialTerm[0] = {exponent, coefficient};  // ISSUE HERE

change to

polynomialArray[index].polynomialTerm[0] = (Term){exponent, coefficient};

Upvotes: 0

Views: 189

Answers (4)

iCoder
iCoder

Reputation: 476

There's an efficiency problem here in your code:

  if(index > (sizeof(polynomialArray)/sizeof(Polynomial)))
      polynomialArray = (Polynomial*)realloc(polynomialArray, index * sizeof(Polynomial));

as polynomialArray is a pointer, I think sizeof(polynomialArray) would always be 4 or 8(64-bit system). So the above if statement will always true as long as index is greater than 0.

Upvotes: 2

DrBeco
DrBeco

Reputation: 11785

You cannot attribute values like that (only during declaration).

You should assign like this:

polynomialArray[index].polynomialTerm[0].exponent = exponent;
polynomialArray[index].polynomialTerm[0].coefficient = coefficient;

About the other question, you really don't need assert here. The pointer will not be NULL if it has a value malloc allocated to it. If not, it is better to be NULL, so you can test if malloc failed.

To have it ordered, you will need to order using some sort algorithm. I think that if you are looking for an easy way, the way you are doing is fine. If it is critical to be ordered (like real time applications), than you need to rethink the approach. If not, keep it and go forward!

Take care, Beco

Upvotes: 0

Richard Pennington
Richard Pennington

Reputation: 19965

If this is C99, I think you need

polynomialArray[index].polynomialTerm[0] = (Term){exponent, coefficient};

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76888

polynomialArray[index].polynomialTerm[0]->exponent = exponent;
polynomialArray[index].polynomialTerm[0]->coefficient = coefficient; 

Upvotes: 2

Related Questions