在我的链表中,我试图避免malloc
添加一个额外的节点而不添加一堆if
语句等。我有以下内容:
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;
}
但是当我去打印多项式时(我有一个完美的函数),我得到以下信息:
Polynomial 1: 3x^4
--> 在这种情况下,对 head->next 的引用为 NULL
所以我尝试了以下解决方法 - 只需提前为新节点分配内存,但前提是这将是用户输入的最后一次迭代。这是通过以下方式完成的:
替换temp->next = NULL;
为
if((numTerms - 1) != counter) temp->next = malloc(sizeof(term));
防止添加“numTerms - 1
额外节点”,malloc 是为了保持对 temp->next 的引用。如果我不使用if
检查并且总是分配额外的内存,我最终会得到以下结果:
Polynomial 1: 3x^4 - 7x^2 + 5 + 10621224x^10617028
我缺少分配的哪一部分导致对 temp->next 的引用丢失?一般来说,我对指针和内存管理真的很糟糕,所以这可能是一个可怕的问题。