2

使用链表创建字典数据结构。

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 类型

4

2 回答 2

7

next是 a struct dictionary_entry_t *,但是d->curr是 a dictionary_entry_t *aka struct _dictionary_entry_t *。注意下划线的区别。

解决此问题的一种方法是与您的下划线保持一致,声明next为:

struct _dictionary_entry_t *next;

但是,我更喜欢另一种方式:typedef在声明struct. 然后:

typedef struct _dictionary_entry_t dictionary_entry_t;
struct _dictionary_entry_t {
    /* ... */
    dictionary_entry_t *next;
    /* ... */
};
于 2013-09-08T22:41:22.267 回答
2

除了@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))
于 2013-09-08T22:44:49.230 回答