Programming in C

(Barry) #1

258 Chapter 11 Pointers


printf ("Enter value to locate: ");
scanf ("%i", &search);

listPtr = findEntry (listStart, search);

if ( listPtr != (struct entry *) 0 )
printf ("Found %i.\n", listPtr->value);
else
printf ("Not found.\n");

return 0;
}

Program 11.10 Output
Enter value to locate: 200
Found 200.

Program 11.10 Output (Rerun)
Enter value to locate: 400
Not found.

Program 11.10 Output (Second Rerun)
Enter value to locate: 300
Found 300.

The function header
struct entry *findEntry (struct entry *listPtr, int match)
specifies that the function findEntryreturns a pointer to an entrystructure and that it
takes such a pointer as its first argument and an integer as its second.The function begins
by entering a whileloop to sequence through the elements of the list.This loop is exe-
cuted until either matchis found equal to one of the valueentries in the list (in which
case the value of listPtris immediately returned) or until the null pointer is reached
(in which case the whileloop is exited and a null pointer is returned).
After setting up the list as in previous programs, the mainroutine asks the user for a
value to locate in the list and then calls the findEntryfunction with a pointer to the
start of the list (listStart) and the value entered by the user (search) as arguments.
The pointer that is returned by findEntryis assigned to the struct entrypointer
variable listPtr. If listPtris not null, the valuemember pointed to by listPtris

Program 11.10 Continued
Free download pdf