How to check if a list is empty? If I do "if (ptr!=NULL)" it doesn't work

Viewed 54

This is a part of a program that should moves a card from a stack and puts it to topstacks.

struct card {
    char face[3];
    char suit[4];
};
typedef struct card Card;

struct stack {
    Card cardd;
    struct stack *nextPtr;
};
typedef struct stack Stack;

int main() {
    Card deck[52];
    fill_deck(deck);
    randomize_deck(deck);
    Stack *stacks = calloc(10, sizeof(Stack));
    make_stacks(deck, stacks);    // all 10 stacks are filled with cards
    Stack *topstacks = calloc(4, sizeof(Stack));    // all 4 topstacks are EMPTY.
    /*
    scanf pos1, pos2 needed to apply the move the card in move_card
    */
    move_card(stacks, topstacks, pos1, pos2);
}

int move_card(Stack *stacks, Stack *topstacks, unsigned int pos1, unsigned int pos2) {
    Stack *prevfromPtr;
    Stack *fromPtr = &(stacks[pos1]);
    Stack *toPtr = &(topstacks[pos2]); 
    while (fromPtr->nextPtr != NULL) {
        prevfromPtr = fromPtr;
        fromPtr = fromPtr->nextPtr;
    }
    Stack *newmovingcard = calloc(1, sizeof(Stack));
    newmovingcard->cardd = fromPtr->cardd;
    newmovingcard->nextPtr = NULL; 
    if (toPtr != NULL) {    // this does not work. toPtr appears to be ALWAYS nonNULL, when it actually is NULL.
        while (toPtr->nextPtr != NULL) {
            toPtr = toPtr->nextPtr;
        } 
        toPtr->nextPtr = newmovingcard; 
        free(fromPtr);
        prevfromPtr->nextPtr = NULL;
        return 0;
    } else {
        toPtr->cardd = newmovingcard->cardd;
        toPtr->nextPtr = NULL;
        free(fromPtr);
        prevfromPtr->nextPtr = NULL;
        return 0;
    }
}

I don't know why, in move_card function, when I do if (toPtr!=NULL), it appears non NULL, when actually toPtr is pointing to an empty list. So why does this happen?

This is the full code: https://hastebin.com/adikunevus.cpp

I'm sorry but the printf part is in Italian, but basically, if you select the 2 choice and then you choose which column of game stacks takes the card, and then you choose the column of base stacks to bring the card (so basically the program executes the move_card function), it does not work because it goes inside the if (toPtr != NULL) when it shouldn't.

So I don't get what I am doing wrong.

0 Answers
Related