Programming in C

(Barry) #1
Pointers and Arrays 259

displayed.This should be the same as the value entered by the user. If listPtris null,
then a “Not found.” message is displayed.
The program’s output verifies that the values 200 and 300 were correctly located in
the list, and the value 400 was not found because it did not, in fact, exist in the list.
The pointer that is returned by the findEntryfunction in the program does not
seem to serve any useful purpose. However, in more practical situations, this pointer
might be used to access other elements contained in the particular entry of the list. For
example, you could have a linked list of your dictionary entries from Chapter 10,
“Character Strings.”Then, you could call the findEntryfunction (or rename it lookup
as it was called in that chapter) to search the linked list of dictionary entries for the
given word.The pointer returned by the lookupfunction could then be used to access
the definitionmember of the entry.
Organizing the dictionary as a linked list has several advantages. Inserting a new word
into the dictionary is easy: After determining where in the list the new entry is to be
inserted, it can be done by simply adjusting some pointers, as illustrated earlier in this
chapter. Removing an entry from the dictionary is also simple. Finally, as you learn in
Chapter 17, this approach also provides the framework that enables you to dynamically
expand the size of the dictionary.
However, the linked list approach for the organization of the dictionary does suffer
from one major drawback:You cannot apply your fast binary search algorithm to such a
list.This algorithm only works with an array of elements that can be directly indexed.
Unfortunately, there is no faster way to search your linked list other than by a straight,
sequential search because each entry in the list can only be accessed from the
previous one.
One way to glean the benefits of easy insertion and removal of elements, as well as
fast search time, is by using a different type of data structure known as a tree.Other
approaches, such as using hash tables,are also feasible.The reader is respectfully referred
elsewhere—such as to The Art of Computer Programming,Volume 3, Sorting and Searching
(Donald E. Knuth, Addison-Wesley)—for discussion of these types of data structures,
which can be easily implemented in C with the techniques already described.


Pointers and Arrays


One of the most common uses of pointers in C is as pointers to arrays.The main reasons
for using pointers to arrays are ones of notational convenience and of program efficiency.
Pointers to arrays generally result in code that uses less memory and executes faster.The
reason for this will become apparent through our discussions in this section.
If you have an array of 100 integers called values,you can define a pointer called
valuesPtr, which can be used to access the integers contained in this array with the
statement


int *valuesPtr;

Free download pdf