使用getc获取奇怪的角色?

时间:2015-12-30 23:11:02

标签: c getchar

所以我开始实现一个Huffman树,为此,我试图从stdin或输入文件中获取字符值。输入文件(只是一个字符串" cheese")被添加到数组freqcounts中,其中要添加的freqcounts的索引是它读取的字符的ascii转换。现在,它为字符串做了这个(e被添加到索引101等)但是然后有所有这些随机字符(朝向数组的末尾,我认为它们可能是空字符?)正在添加,带有数字成千上万。谁能向我解释一下发生了什么?

    int main(int argc, const char * argv[]) {
    int ch; //character to be used for getch
    int freqcounts[R];
    while(1){
        /*Something weird going on in here*/
        /*I'm getting the proper characters (supposed to be cheese) but then there are all these random nullesque characters
         with absurd counts that is fucking up my linked list*/
        ch=getc(stdin);
        if (ch == EOF){ //eof
            freqcounts[0]=1;
            break;
        }
        else{
            freqcounts[ch]++;
        }
    }
    for (int i=0; i< R; i++){
        printf("%d", freqcounts[i]);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

主要问题是数组:freqcounts []未初始化为全0。

建议将其声明如下:

int freqcounts[R] = {0};