In my linked list, I'm trying to avoid mallocing an extra node without adding a bunch of if statements and such. I have the following:
polynomial create()
{
polynomial head = NULL;
polynomial temp = NULL;
int numTerms, coefficient, exponent;
int counter = 0;
printf("Enter the number of terms in the polynomial: ");
scanf ("%d", &numTerms);
printf("\n");
if (numTerms == 0) {
head = malloc(sizeof(term));
head->coef = 0; head->exp = 0; head->next = NULL;
return head;
}
while (numTerms != counter) {
// Ask for input
printf("Enter the coefficient and exponent of term %d: ", (counter + 1));
scanf("%d %d", &coefficient, &exponent);
printf("\n");
// Create the term
if (temp == NULL) temp = malloc(sizeof(term));
temp->coef = coefficient; temp->exp = exponent; temp->next = NULL;
//if((numTerms - 1) != counter) temp->next = malloc(sizeof(term)); -- this is my workaround
printf("Created: %d %d\n", temp->coef, temp->exp);
// If this is the first node created, mark the head
if (counter == 0) head = temp;
// Increment the list and counter
temp = temp->next;
counter ++;
}
return head;
}
But when I go to print the polynomial (I have a function that works perfectly to do so), I get the following:
Polynomial 1: 3x^4 --> in this case, the reference to head->next is NULL
So I tried the following workaround - just allocate memory in advance for new nodes, but only if this would be the last iteration of user input. This is accomplished by:
replace temp->next = NULL; with
if((numTerms - 1) != counter) temp->next = malloc(sizeof(term));
The numTerms - 1 prevents adding the 'extra node', and the malloc is to keep the reference to temp->next alive. If I don't use the if check and just always allocate extra memory, I end up with the following:
Polynomial 1: 3x^4 - 7x^2 + 5 + 10621224x^10617028
What part of allocation am I missing that causes the reference to temp->next to be lost? I'm really really terrible with pointers and memory management in general, so this is probably a terrible question.
mallocexactly?