[英]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? 但是last-> pt无法转换为temp,我该如何解决这个问题呢?
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
}
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
. 它最初编写的方式,它将last
作为(单个)指针处理,并尝试取消引用成员pt
。 Instead, you want to dereference last
, and then access member pt
of the resulting pointer. 相反,您想要取消引用last
,然后访问结果指针的成员pt
。
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是该结构的成员,那么
p->m
selects that member of the pointed-to structure. 选择指向结构的成员。 The expression p->m is therefore exactly equivalent to 因此,表达式p-> m完全等同于
(*p).m
You on the other hand are using some vague combination. 另一方面,你正在使用一些模糊的组合。 Use either format. 使用任一格式。 Eg last->pt
or (*last).pt
例如last->pt
或(*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. (假设您要更改指针指向的地址。如果在其前面使用星号,则表示您正在与指针指向的实际值进行比较/分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.