4

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

2 Answers 2

8

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: typedeffing before declaring the struct. Then:

typedef struct _dictionary_entry_t dictionary_entry_t;
struct _dictionary_entry_t {
    /* ... */
    dictionary_entry_t *next;
    /* ... */
};
Sign up to request clarification or add additional context in comments.

Comments

2

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))

1 Comment

I didn't even think about this either. Appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.