所以我正在尝试将卡片添加到玩家的手中......如果我使用顶部和最后一张牌的双指针,卡片的价值将仅传递回主函数。但是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
}
答案 0 :(得分:2)
问题似乎是运算符优先级,因此使用括号应解决它:
(*last)->pt = temp;
最初编写它的方式是将last
视为(单个)指针,并尝试取消引用成员pt
。相反,您要取消引用last
,然后访问结果指针的成员pt
。
答案 1 :(得分:2)
由于指向结构的指针是常见的,并且上面示例中的括号是令人讨厌的,因此还有另一个结构选择运算符,它用于指向结构的指针。如果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;
(假设您要更改指针所指向的地址。如果您在其前面使用星号,则表示您正在与指针指向的实际值进行比较/分配。