我想清除一個列表。我不斷收到一個錯誤,說free()調用未分配的指針當前。我不確定問題是什麼,我看到多個網站使用此代碼。在C爲什麼我的清單功能不起作用
這是整個程序的要求: 我只是想填寫這三個功能。
#include "orderedList.h"
Node *orderedInsert(Node *p, int newval)
/* Allocates a new Node with data value newval
and inserts into the ordered list with
first node pointer p in such a way that the
data values in the modified list are in
nondecreasing order as the list is traversed.
*/
{
Node * q = NULL;
q = (Node*)malloc(sizeof(Node));
q->data = newval;
q->next = NULL;
if (q == NULL)
{
return q;
}
if (p == NULL || newval <= p->data)
{
q->next = p->next;
return q;
}
Node *tmp, *last;
tmp = (Node*)malloc(sizeof(Node));
tmp = p;
while (tmp->next != NULL && tmp->data <= newval)
{
last = tmp;
tmp = tmp->next;
}
q->next = tmp;
last->next = q;
return p;
}
void printList(FILE *outfile, Node *p)
/* Prints the data values in the list with
first node pointer p from first to last,
with a space between successive values.
Prints a newline at the end of the list.
*/
{
Node* temp = p;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
void clearList(Node **p)
/* Deletes all the nodes in the list with
first node pointer *p, resulting in *p
having value NULL. Note that we are passing
a pointer by address so we can modify that
pointer.
*/
{
Node* current = *p;
Node* temp;
while(current != NULL)
{
temp = current->next;
free(current);
current = temp;
}
*p = NULL;
}
創建列表的元件不使用'malloc'家族。 – BLUEPIXY 2014-12-05 20:07:32
我仍然是初學者,我會在哪裏使用malloc? – Sephiroth 2014-12-05 20:14:56
當您創建列表的元素時使用。 – BLUEPIXY 2014-12-05 20:16:34