简体   繁体   中英

C - Freeing the allocated memory of the struct using a function with ** parameter

So I've got a problem with a function that frees the allocated memory of a dictionary type.
Here's struct I use and function:

struct word_count_t {
    char *word;
    int counter; //how many times word was repeated
};

struct dictionary_t
{
    int size; //number of words
    int capacity; //capacity of wc
    struct word_count_t *wc; //pointer to words 
};


void destroy_dictionary(struct dictionary_t** d) 
{
    if(d == NULL) return;
    int i;
    for(i = 0; i < d->size; i++)
    {
        free(d->wc->word+i);
    }
    free(d->wc);
    free(d);
}   

It was compilating when the function declaration was like this:

void destroy_dictionary(struct dictionary_t* d)

I don't know how to make dereference here if it's needed and get rid of errors like:

[Error] request for member 'size' in '* d', which is of pointer type 'dictionary_t*' (maybe you meant to use '->' ?)

Since d is double pointer it takes pointer address as its input. So first you need to reference pointer address which d is holding using * operator. you cannot directly reference size and wc members using d . I would suggest you to only use double pointer if you want to change the actual pointer.

You need to define your destroy_dictionary as below.

void destroy_dictionary(struct dictionary_t** d) 
{
   if(d==NULL || *d == NULL) return;
   int i;
   for(i=0; i<(*d)->size; i++)
   {
      free((*d)->wc->word+i);
   }
   free((*d)->wc);
   free(*d);
   *d = NULL:
}

You need to dereference d first.

for (i = 0; i < (*d)->size; i++)
{
    free((*d)->wc->word+i);
}

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