-3

So I'm starting to implement a Huffman tree, and to do that, I'm trying to get character values from stdin or a input file. The input file (just a string "cheese") is being added to the array freqcounts, where the index of freqcounts that is being added to is the ascii conversion of the character it reads. Now, it does that for the string (e is added to index 101, etc.) But then there are all these random characters (towards the end of the array, I think they might be null characters?) Being added, with numbers in the tens of thousands. Can anyone explain to me what's going on?

    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;
}
  • 5
    You never set the initial values of the array to something useful (such as `0`) so it contains random values. – Jongware Dec 30 '15 at 23:13
  • Excuse me, Also the constant R is equal to 256 – Joseph Doob Dec 30 '15 at 23:15
  • @Jongware what is the best way to do that? – Joseph Doob Dec 30 '15 at 23:15
  • 3
    `int freqcounts[R] = { 0 };` – M.M Dec 30 '15 at 23:19
  • Figured it out. Thanks alot! – Joseph Doob Dec 30 '15 at 23:20
  • Your build process and/or IDE should help you find these mistakes. Try the /Wall switch for your compiler (if it has it, or something similar, to amp up the warnings). Also, try a [lint](https://en.wikipedia.org/wiki/Lint_(software)) program like [SPLint](http://www.splint.org/), which does say "Value freqcounts[] used before definition" to `freqcounts[ch]++;`. It could be a bit much to learn right away. If so, come back to it. – Tom Blodget Jan 01 '16 at 00:26

1 Answers1

1

the main problem is the array: freqcounts[] is not initialized to all 0s.

Suggest declaring it as follows:

int freqcounts[R] = {0};
user3629249
  • 16,402
  • 1
  • 16
  • 17