【问题标题】:C - Freeing the allocated memory of the struct using a function with ** parameterC - 使用带有 ** 参数的函数释放结构的分配内存
【发布时间】:2019-01-19 00:45:03
【问题描述】:

所以我遇到了一个释放字典类型分配内存的函数的问题。
这是我使用的结构和功能:

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

函数声明的时候是这样编译的:

void destroy_dictionary(struct dictionary_t* d)

如果需要,我不知道如何在此处取消引用并消除以下错误:

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

【问题讨论】:

  • 代码错误现在。给定函数体,参数应该是单次间接,如最后一行所示。如果有错误,请告诉我们那些是什么逐字。如果要求使用双间接(struct dictionary_t **),那么整个body都要改变,d的所有实例都需要替换成(*d)。 (显然,参数列表本身除外)。
  • struct dictionary_t **d 传递给函数的唯一原因是您可以使用*d = NULL; 结束函数。如果您不这样做,您应该将常规的struct dictionary_t *d 传递给该函数以避免您遇到的问题。使用指向指针的指针对函数进行编码的一种方法是在顶部使用struct dictionary *dp = *d;,并在整个过程中使用dp,除了末尾的*d = NULL; 行。
  • ** 通常用于函数要更改传递给函数的指针的值时,即在最后一行写 *d=NULL 时。由于您不更改指针的值,因此双精度 ** 很少有意义,您应该继续使用 void destroy_dictionary(struct dictionary_t* d)

标签: c pointers struct free dereference


【解决方案1】:

您需要先取消引用d

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

【讨论】:

    【解决方案2】:

    由于d 是双指针,它以指针地址作为输入。因此,首先您需要使用 * 运算符引用 d 持有的指针地址。您不能使用d 直接引用sizewc 成员。如果你想改变实际的指针,我建议你只使用双指针。

    您需要如下定义您的 destroy_dictionary。

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

    【讨论】:

    • @Amandin 没有必要将此参数作为双重间接传递,除非意图是在完成此操作后将调用者指针设为空。因此,我强烈建议您将*d = NULL; 作为函数的最后一行。
    • @WhozCraig 采纳了这个建议。
    猜你喜欢
    • 2012-11-06
    • 2018-01-29
    • 2023-03-15
    • 1970-01-01
    • 2017-05-07
    • 2020-05-25
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    相关资源
    最近更新 更多