[英]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类型
next
是struct dictionary_entry_t *
,但是d->curr
是dictionary_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->curr
为NULL
,那么当你执行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.