首页 > 解决方案 > free 参数 1 的不兼容类型

问题描述

当我尝试释放我创建的元组数组时出现此错误。

这是发生错误的地方:

void free_freq_words(Tuple *freq_words, int num)
{
  int i;

  for (i = 0; i < num; i++)
  {
     free(freq_words[i].word);
     free(freq_words[i]); /******* error here *********/
  }
}

我创建了这样的元组数组:

Tuple *freq_words = (Tuple *) malloc(sizeof(Tuple) * num);

以下是元组的定义方式:

typedef struct Tuple
{
   int freq;
   char *word;
} Tuple;

请注意,我很确定我必须在释放元组本身之前释放单词,因为我为每个单词分配空间:

freq_words[num - 1].word = (char *) malloc(sizeof(char) * strlen(word) + 1);

我得到的错误是第二个免费的:

fw.c: In function âfree_freq_wordsâ:
fw.c:164:7: error: incompatible type for argument 1 of âfreeâ
       free(freq_words[i]);
       ^
In file included from fw.c:3:0:
/usr/include/stdlib.h:482:13: note: expected âvoid *â but argument is of type âT
upleâ
 extern void free (void *__ptr) __THROW;

我在释放之前尝试施放,但没有奏效:

fw.c: In function âfree_freq_wordsâ:
fw.c:164:7: error: cannot convert to a pointer type
   free((void *) freq_words[i]);

我以前从来没有遇到过免费的错误,除非我尝试两次释放相同的东西,所以我不知道该怎么做。我四处搜索,但找不到太多。我应该如何更改我的代码以便免费工作?

标签: cfree

解决方案


分配是:Tuple *freq_words = (Tuple *) malloc(sizeof(Tuple) * num);

取消分配是:free(freq_words);


推荐阅读