Double pointers to add an element to a linked list

332 views Asked by At

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
}
2

There are 2 answers

0
Peter Bloomfield On BEST ANSWER

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.

1
edwardmp On

Since pointers to structures are common, and the parentheses in the example above are a nuisance, there's another structure selection operator which works on pointers to structures. If p is a pointer to a structure and m is a member of that structure, then

p->m

selects that member of the pointed-to structure. The expression p->m is therefore exactly equivalent to

(*p).m

You on the other hand are using some vague combination. Use either format. E.g. last->pt or (*last).pt

Also these lines contain asterisks that don't belong there I believe:

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

All together, this should work:

if(top == NULL)
    top = temp;
else
    last->pt = temp;
last = temp;

(Assuming you want to change the address the pointer is pointing to. If you use a asterisk in front of it you are comparing/assigning with the actual value the pointer is pointing to.