简体   繁体   中英

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. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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