使用链接列表创建字典数据结构.
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;
Run Code Online (Sandbox Code Playgroud)
使用函数将字典条目添加到链表.
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;
}
Run Code Online (Sandbox Code Playgroud)
将d-> curr分配给d-> curr-> next给我警告'从不兼容的指针类型分配'.
这里我的错误是什么?curr和next都是*dictionary_entry_t类型
next是一个struct dictionary_entry_t *,但是d->curr一个dictionary_entry_t *又名struct _dictionary_entry_t *.注意下划线的区别.
解决此问题的一种方法是与您的下划线保持一致,声明next为:
struct _dictionary_entry_t *next;
Run Code Online (Sandbox Code Playgroud)
但是,我更喜欢一种不同的方式:typedef在声明之前fing struct.然后:
typedef struct _dictionary_entry_t dictionary_entry_t;
struct _dictionary_entry_t {
/* ... */
dictionary_entry_t *next;
/* ... */
};
Run Code Online (Sandbox Code Playgroud)