Search code examples
csingly-linked-listdouble-pointer

Double pointers to add an element to a linked list


So I'm trying to add a card to a player's hand... and the value of the card will only be passed back to the main function if I use a double pointer for the top and last cards. But last->pt can't translate to temp, how do I fix this?

typedef struct card_s
{
char suit[9];
int value;
struct card_s *pt;
} card;

void deal_card(card **top, card **last, card dealt)
{
card *temp;

temp = (card*)malloc(sizeof(card));
strcpy(temp->suit, dealt.suit);
temp->value = dealt.value;

if(*top == NULL)
    *top = temp;
else
    *last->pt = temp; //FIX ME - something is going wrong at this point
*last = temp;
last->pt = NULL; //FIX ME - same problem as above
}

Solution

  • The problem seems to be operator precedence, so using parentheses should resolve it:

    (*last)->pt = temp;
    

    The way it was written originally, it was treating last as a (single) pointer, and trying to dereference member pt. Instead, you want to dereference last, and then access member pt of the resulting pointer.