简体   繁体   中英

Assignment from incompatible pointer type (structs, linked list)

Creating a dictionary data structure using a 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;

Working on the function to add dictionary entries to the linked list.

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;
}

assigning d->curr to d->curr->next gives me the warning 'assignment from incompatible pointer type'.

What is my mistake here? both curr and next are of the type *dictionary_entry_t

next is a struct dictionary_entry_t * , but d->curr is a dictionary_entry_t * aka struct _dictionary_entry_t * . Note the difference in underscores.

One way to solve this would be to be consistent with your underscores, declaring next as:

struct _dictionary_entry_t *next;

However, I prefer a different way: typedef fing before declaring the struct . Then:

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

In addition to the issue raised by @icktoofay, another problem is your loop condition:

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

If d->curr is NULL , then when you do the strcmp() , you're attempting to dereference a NULL pointer. Bad things will happen. Reverse those:

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

Or, more concisely:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM