【发布时间】: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