Objects First |
Once we've cleared up the ambiguities, we start designing the software.
Following the step-by-step approach:
|
Somewhere in between, there will be a set of 'reasonable'
names.
In this case,
the obvious one is
It's not too long and is the same term used in the specification. |
Other possibilities are:
|
Click here to load
the software specification.
I suggest that you re-size the windows to make two long ones
side-by-side so that you can scroll through the code in one and
these notes in the other.
We derived this constructor by observing that the requirements state:
Dictionaries have a fixed maximum size - specified when they're built.Add a destructor which frees the memory allocated by a constructor.
If it matches precisely ..
Note that in this case, the checking of a word passed as a parameter to a method involves
#define VALID_WORD(w) assert(w!=NULL);assert(strlen(w)>0); \
assert( (*w>='a') && (*w<='z') );
Notes:
We could also add a reasonableness check which verified that
words were not longer than some reasonable maximum.
The longest word in English is generally reckoned to have 28
letters, so that adding:
#define MAX_WORD_CHARS 28
#define VALID_WORD(w) assert(w!=NULL);assert(strlen(w)>0); \
assert(strlen(w)<=MAX_WORD_CHARS); \
assert( (*w>='a') && (*w<='z') );
would make our code even more robust.
In this exercise, we want to construct arrays of characters strings - one array, English, with English words and the other, Foreign, containing the foreign words. Whenever we want to dynamically allocate space for an array by using malloc or calloc, we declare a pointer to the type of elements of the array. Here, the elements of the array are strings, and strings are represented by character pointers or char *. Therefore both English and Foreign are declared as char ** or pointers to character pointers. Think of English as an array (one of the *'s) of strings (the other *).
There are 3 malloc calls -
Not unsurprisingly, DeleteDictionary has 3 free calls - one to free each block of space malloc'd in the constructor.
Observe that we have used strdup to make a copy of the word we're storing in the dictionary. This is to ensure that we've "captured" the appropriate word for storage in the dictionary. This allows the user to re-use the buffer in which the new words were placed. Look in the testing program and see how we simply set pointers to the word starting positions in the read buffer used by fgets. The buffer was used again for the next word read from the file.
|
Continue on to Verifying the Class Back to the Table of Contents |