因此,我开始实现霍夫曼树,并且为此,我尝试从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;
}
最佳答案
主要问题是数组:freqcounts []未初始化为全0。
建议声明如下:
int freqcounts[R] = {0};