From: Joerg B. <jo...@sq...> - 2000-10-19 17:54:09
|
Hi Jim ! Jim Sheetz wrote: > > OK, I've got another one. I have data coming in to a program from a file. > The program finds the length of all the words in the file, and prints a > histogram to the screen of how many words are of each length. Given that in > good programming practice, you have to assume the data can be anything, I > can't assume a length of the longest word. Here's the problem. I think the > most efficient way of dealing with this is to stuff all these numbers into > an array with length[1] being the count of words that are 1 char long. > length[2] is the count of words that are 2 chars long, etc. Until I go all > the way through the data, I don't know how long the longest word is, so I > can't declare the array because I don't know how many elements there are. > But I can't put the data in the array without declaring it first. In other > languages I've worked with, it is encouraged to declare and dimension an > array before using it, but you can add elements to an array without doing > so. I can't find any method of doing that in C. Am I just not looking far > enough, or is there a better solution? As usual, there are many ways - this is just what comes to my mind: 1) Assume some realistic limit. "Screen" indicates 24 lines, so anything much larger might change the way the program can be used. 2) Assume some arbitrary large limit - say 1,000. 3) Check the maximum possible line length of your input, probably words can not get larger than a single line. 4) Define the array of unknown size, use "malloc" to get storage for some initial size (100 ?). Access it via the pointer returned by "malloc". If you encounter a word that is longer than the currently valid array definition, use "realloc" to grow it. 4) Use Perl or any other language that has dynamically growing arrays. Waiting for the other proposals ... Joerg Bruehe -- Joerg Bruehe, SQL Datenbanksysteme GmbH, Berlin, Germany (speaking only for himself) mailto: jo...@sq... |