Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 单词计数器“忘记”已保存的单词_C_Struct - Fatal编程技术网

C 单词计数器“忘记”已保存的单词

C 单词计数器“忘记”已保存的单词,c,struct,C,Struct,下面的代码段来自我的程序,它获取单词,然后打印出单词出现的次数 它几乎可以正常工作,只是它忽略了以前保存过的特定条目,并且不增加与之关联的计数器 typedef struct { char *word; int occ; } words; words *data=NULL; int main(int argc, char **argv) { char *word; words *temp; int c,i,num; words *ptr = NU

下面的代码段来自我的程序,它获取单词,然后打印出单词出现的次数

它几乎可以正常工作,只是它忽略了以前保存过的特定条目,并且不增加与之关联的计数器

typedef struct {
    char *word;
    int occ;
}
words;
words *data=NULL;

int main(int argc, char **argv)
{
    char *word;
    words *temp;
    int c,i,num;
    words *ptr = NULL;

    num=0;

    while(1)
    {
        c=fgetc(infile);
        if(c==EOF) break;
        if(!isalpha(c)) continue;
        else ungetc(c,infile);
        word=getword(infile);

        if(findword(word))
        {

            if(!(temp=realloc(data,sizeof(words)*(num+1))))
            { /* error handling */ }
            else
                data=temp;



        }
        else
           free(word);
    }

    /* sort procedure here, irrelevant for the purpose of topic */
    for(i=0;i<num;i++)
    {
        /*printf*/
    }

    return 0;

}
那代码怎么了


提前谢谢

根本问题是findword函数实际上找不到单词;它只是查看列表中的一项。它需要循环。

添加单词的逻辑在哪里?你只是比较它们然后继续。你的代码都出了问题,是H.W吗?从使用全局变量数据开始,然后从函数返回它,这有什么意义??然后不存在一个数据->字的分配,您只分配了一个指针,而没有为字符串本身分配空间,等等,这是非常糟糕的代码!我不是有意暗示找不到这个词是唯一的问题-/@twalberg如果它找到了一个词,那么如果findword中的条件为false,那么它将在main中的其他位置对特定的ptr->occ进行递增。@Peter Kowalski:是的,但即使这样也不能正常工作,因为所使用的ptr是main的本地ptr,并且只有在前一次while 1迭代中设置或保留。事实上,代码的行为方式让我想知道,包括findword在内的命名是否误导了我,它实际上只是试图识别连续重复的单词。你想把它打印出来做什么?
if ((strcmp(word, ptr->word)) == 0) {
  //Do something to store the count
} 
else {
  return ptr;
}