Programming in C

(Barry) #1

220 Chapter 10 Character Strings


In the preceding structure definition, you have defined enough space for a 14-letter
word (remember, you are dealing with variable-length character strings, so you need to
leave room for the null character) plus a 49-character definition.The following is an
example of a variable defined to be of type struct entrythat is initialized to contain
the word “blob” and its definition.
struct entry word1 = { "blob", "an amorphous mass" };
Because you want to provide for many words inside your dictionary, it seems logical to
define an array of entrystructures, such as in
struct entry dictionary[100];
which allows for a dictionary of 100 words. Obviously, this is far from sufficient if you
are interested in setting up an English language dictionary, which requires at least
100,000 entries to be of any value. In that case, you would probably adopt a more
sophisticated approach, one that would typically involve storing the dictionary on the
computer’s disk, as opposed to storing its entire contents in memory.
Having defined the structure of your dictionary, you should now think a bit about its
organization. Most dictionaries are organized alphabetically. It makes sense to organize
yours the same way. For now, assume that this is because it makes the dictionary easier to
read. Later, you see the real motivation for such an organization.
Now, it’s time to think about the development of the program. It is convenient to
define a function to look up a word inside the dictionary. If the word is found, the func-
tion could return the entry number of the word inside the dictionary; otherwise, the
function could return –1 to indicate that the word was not found in the dictionary. So, a
typical call to this function, which you can call lookup, might appear as follows:
entry = lookup (dictionary, word, entries);
In this case, the lookupfunction searches dictionaryfor the word as contained in the
character string word.The third argument,entries,represents the number of entries in
the dictionary.The function searches the dictionary for the specified word and returns
the entry number in the dictionary if the word is found, or returns –1 if the word is not
found.
In Program 10.9, the lookupfunction uses the equalStringsfunction defined in
Program 10.4 to determine if the specified word matches an entry in the dictionary.

Program 10.9 Using the Dictionary Lookup Program
// Program to use the dictionary lookup program

#include <stdio.h>
#include <stdbool.h>

struct entry
{
char word[15];
Free download pdf