Task: Write a program that prints the histograms of the frequencies of input characters

To decide how best to declare an array, define all the characters in it in advance, or add them to the array as they occur in the stream (ie, if such a symbol is the first in the array, then create a cell to calculate this symbol)? Thank!

  • C has a very complicated relationship with working with memory (compared to garbage collection languages), and dynamically adding elements is not so easy there, so in the case of a small known size (this is your case, 256 or 128 values ​​of 4 bytes is just only kilobyte or half kilobyte) is easier to allocate immediately. @PinkTux wrote everything correctly. - etki

1 answer 1

If you have single-byte encoding, or it is only about Latin (which is obvious in the case of K & R), then it is enough to create an array in advance:

size_t char_freq[256] = { 0 }; 

And when entering a symbol, simply increment the counter, using the symbol as an index in it:

 char_freq[ch]++; 
  • Understood thanks! But as far as I understand, Latin is in single-byte encoding! Therefore, for all the characters your code is suitable! - ActiveNum
  • @ActiveNum, but it will not work, for example, for Russian in UTF8 (and here in windows-1251 - quite). But since this is a task from K & R, such details are clearly not meant :-) - PinkTux