簡體   English   中英

從不兼容的指針類型(結構,鏈表)分配

[英]Assignment from incompatible pointer type (structs, linked list)

使用鏈接列表創建字典數據結構。

typedef struct _dictionary_entry_t
{
    const char* key;
    const char* value;
    struct dictionary_entry_t *next;
    struct dictionary_entry_t *prev;

} dictionary_entry_t;

typedef struct _dictionary_t
{   
    dictionary_entry_t *head;
    dictionary_entry_t *curr;
    int size; 

} dictionary_t;

使用函數將字典條目添加到鏈表。

int dictionary_add(dictionary_t *d, const char *key, const char *value)
{
    if (d->curr == NULL) //then list is empty
    {
        d->head = malloc(sizeof(dictionary_entry_t));
        d->head->key = key;  //set first dictionary entry key
        d->head->value = value; //set first dictionary entry value
        d->head->next = NULL; 
        //d->curr = d->head;
    }

    else 
    {
        d->curr = d->head;

        while (strcmp((d->curr->key), key) != 0 && d->curr != NULL) //while keys don't match and haven't reached end of list... 
        {
            d->curr = d->curr->next; 

        } 
    }


    return -1;
}

將d-> curr分配給d-> curr-> next給我警告“來自不兼容指針類型的分配”。

我這是什么錯 curr和next均為* dictionary_entry_t類型

nextstruct dictionary_entry_t * ,但是d->currdictionary_entry_t * aka struct _dictionary_entry_t * 注意下划線的區別。

解決此問題的一種方法是與您的下划線保持一致, next聲明為:

struct _dictionary_entry_t *next;

但是,我更喜歡另一種方式:在聲明struct之前先輸入typedef fing。 然后:

typedef struct _dictionary_entry_t dictionary_entry_t;
struct _dictionary_entry_t {
    /* ... */
    dictionary_entry_t *next;
    /* ... */
};

除了@icktoofay引發的問題外,另一個問題是循環條件:

while (strcmp((d->curr->key), key) != 0 && d->curr != NULL)

如果d->currNULL ,那么當你執行strcmp() ,你試圖取消引用NULL指針。 壞事會發生。 反轉那些:

while ((d->curr != NULL) && strcmp(d->curr->key, key) != 0)

或者,更簡潔:

while (d->curr && strcmp (d->cur->key, key))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM