简体   繁体   English

链表C中的无限while循环

[英]Infinite while loop in linked list C

I ran into a problem, I want to add item to the end of the linked list, but it seems that i am getting sucked in an infinite loop here. 我遇到了一个问题,我想在链表的末尾添加项目,但是似乎我在这里陷入了无限循环。

void addCheckPoint(struct checkPoints **checkPoint) {
    struct checkPoints *checkPt = *checkPoint;

    while (checkPt->next != NULL) {
        checkPt->next;
        if (checkPt->next == NULL) {
            scanf("%c %d %d %d %d", &checkPt->dropOut, &checkPt->currentPoint, &checkPt->competitor, &checkPt->hour, &checkPt->minute);
        }
    }
}

You never update the value of checkPt in your loop. 您永远不会在循环中更新checkPt的值。 Change the line 换线

checkPt->next;

to

checkPt = checkPt->next;

to fix this. 解决这个问题。

Note that there may be further problems with the function. 请注意,该功能可能还有其他问题。 Despite its name, it doesn't actually add anything to the list. 尽管名称如此,它实际上并没有在列表中添加任何内容。 It edits the contents of the tail item instead. 而是编辑尾项的内容。 If this isn't deliberate, you'll need to malloc a new element then add it to the tail. 如果这不是故意的,则需要分配一个新元素,然后将其添加到尾部。

void addCheckPoint(struct checkPoints **checkPoint) {
    struct checkPoints *checkPt = *checkPoint;

    while (checkPt != NULL) {
        if (checkPt->next == NULL) {
            scanf("%c %d %d %d %d", checkPt->dropOut, checkPt->currentPoint, checkPt->competitor, checkPt->hour, checkPt->minute);
        }
        checkPt = checkPt->next;
    }
}

try this 尝试这个

 void addCheckPoint(struct checkPoints **checkPoint) {
        struct checkPoints *checkPt = *checkPoint;

        while (checkPt->next != NULL) {
             checkPt=checkPt->next;
            if (checkPt == NULL) {
                scanf("%c %d %d %d %d", &checkPt->dropOut, &checkPt->currentPoint, &checkPt->competitor, &checkPt->hour, &checkPt->minute);
            }

        }
    }
#include <stdlib.h>
#include <stdio.h>

struct checkPoints
{
    char dropOut;
    int currentPoint;
    int competitor;
    int hour;
    int minute;

  struct checkPoints *next;
};

void addCheckPoint(struct checkPoints **checkPoint) {
    while (*checkPoint)
        checkPoint = &(*checkPoint)->next;

    /* FIXME: check malloc() return value */
    *checkPoint = malloc(sizeof (struct checkPoints));
    (*checkPoint)->next = 0;

    /* NOTE: the leading space in front of the %c */
    scanf(" %c %d %d %d %d",
          &(*checkPoint)->dropOut,
          &(*checkPoint)->currentPoint,
          &(*checkPoint)->competitor,
          &(*checkPoint)->hour,
          &(*checkPoint)->minute);
}

struct checkPoints *list = 0;

int
main ()
{
    addCheckPoint (&list);
    addCheckPoint (&list);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM