将变量与链表的变量进行比较

时间:2016-04-05 09:38:20

标签: c linked-list

我有一个程序,用户可以通过该程序进行调查。它包含具有pps作为唯一标识符的人员的详细信息。将newNode添加到列表并检查PPS时,它无法识别任何节点中的数字是否相同。将printf添加到循环中以显示当前的pps会产生nullptr异常。我已经尝试不使用** head_ptr替换* head_ptr但是这会在节点添加到列表的其余代码中产生更多错误。

//a new node is created which is filled with info. Some vaidation is done such as PPS number uniqueness and the node is added to the list
//in this function the node is added to the very front of the list. Note: the sorting does not happen here without sorting it would be a list of the most recently enetered items
//a second function will carry out the sort
void addSurvey(struct survey** head_ptr)
{

    int inputPPS,inputAge,inputSmoker, inputDrink, inputExer, inputIncome;
    int scanfBoolean;
    struct survey *temp;
    struct survey *newNode;


    temp = *head_ptr;

    newNode = (struct survey*)malloc(sizeof(struct survey));
    printf("\nPlease enter your PPS number (Number must be unique)\n");
    scanf("%d", &inputPPS);
    while (temp != NULL)
    {

        if (inputPPS == temp->surveyDetails.ppsNo)
        {
            printf("\nPPS you have entered is not unique. \n\n");
            free(newNode); free(temp);
            return;
        }
        temp = temp->next;
        printf("\nChecking list. PPS is %d\n\n", temp->surveyDetails.ppsNo);




    }
    newNode->surveyDetails.ppsNo = inputPPS;

2 个答案:

答案 0 :(得分:1)

一旦找到它就会释放节点

free(temp);

在这种情况下,从这个函数addSurvey返回后,struct survey** head_ptr指向的指针指向释放的内存,可能你错误​​地使用了它。

更糟糕的是,当您为temp分配新值并且可能已为其分配了NULL时,您不会检查这个并且您尝试访问指向该未知内存的指针以打印整数:

temp = temp->next;
printf("\nChecking list. PPS is %d\n\n", temp->surveyDetails.ppsNo);

答案 1 :(得分:0)

您不会将新节点(newNode)链接到列表,将列表留空。你必须添加

         TEMP->接着= newNode;

是一个合适的地方