繁体   English   中英

用于将元素添加到链接列表的双指针

[英]Double pointers to add an element to a linked list

所以我正在尝试将一张卡片添加到玩家手中......如果我使用顶部和最后一张牌的双指针,那么该牌的价值将仅传递回主函数。 但是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
}

问题似乎是运算符优先级,因此使用括号应解决它:

(*last)->pt = temp;

它最初编写的方式,它将last作为(单个)指针处理,并尝试取消引用成员pt 相反,您想要取消引用last ,然后访问结果指针的成员pt

由于指向结构的指针是常见的,并且上面示例中的括号是令人讨厌的,因此还有另一个结构选择运算符,它用于指向结构的指针。 如果p是指向结构的指针而m是该结构的成员,那么

p->m

选择指向结构的成员。 因此,表达式p-> m完全等同于

(*p).m

另一方面,你正在使用一些模糊的组合。 使用任一格式。 例如last->pt(*last).pt

这些行还包含不属于那里的星号我相信:

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

总之,这应该工作:

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

(假设您要更改指针指向的地址。如果在其前面使用星号,则表示您正在与指针指向的实际值进行比较/分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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