Basically all I am trying to do is assign something (a Polynomial) to a dynamic array at a given index, overwriting whatever is there. For simplicity I just made subtract() return a pointer to the first element in the polynomialArray. So, this code should copy the contents of the first element and replace another element (I know that a deep copy is necessary, and that is implemented in subtract). I have been spoiled by java (and you kind folks)...
When I go to print it at the index at which it is copied to, there is nothing there.
Usually something like Poly1 = 2x^3 + 4x would print, but instead it just prints Poly1 =.
Compiles fine and runs, but does not do what I need it to. EDIT: Runs fine if there wasn't anything at that index. If there is something at the index, seg fault.
//Portion of main from another file
Polynomial* subtracted = subtract(op1_index, op2_index);
insert(subtracted, diff_index);
printPolynomial(diff_index);
//Methods in question (utils file)
void insert(Polynomial* element, int index) {
if(index > num_polynomial) {
polynomialArray = (Polynomial*)realloc(polynomialArray, (index + 1) * sizeof(Polynomial));
}
free(polynomialArray[index].polynomialTerm);
polynomialArray[index] = *element; // Problem here?
}
Polynomial* subtract(int op1_index, int op2_index) {
return &polynomialArray[0];
}
//Typedefs accessible in main and utils file
typedef struct term {
int exponent;
int coefficient;
} Term;
typedef struct polynomial {
Term *polynomialTerm;
} Polynomial;
//variables accessible in utils file
static Polynomial *polynomialArray;
int num_polynomial; // counter to keep track of the number of polynomials
programming-languagestag to your questions. It's not necessary.