簡體   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