Programming in C

(Barry) #1
Pointers and Functions 257

You should realize that without the use of pointers, you could not have written your
exchangefunction to exchange the value of two integers because you are limited to
returning only a single value from a function and because a function cannot permanent-
ly change the value of its arguments. Study Program 11.9 in detail. It illustrates with a
small example the key concepts to be understood when dealing with pointers in C.
Program 11.10 shows how a function can return a pointer.The program defines a
function called findEntrywhose purpose is to search through a linked list to find a
specified value.When the specified value is found, the program returns a pointer to the
entry in the list. If the desired value is not found, the program returns the null pointer.


Program 11.10 Returning a Pointer from a Function


#include <stdio.h>


struct entry
{
int value;
struct entry *next;
};


struct entry findEntry (struct entry listPtr, int match)
{
while ( listPtr != (struct entry *) 0 )
if ( listPtr->value == match )
return (listPtr);
else
listPtr = listPtr->next;


return (struct entry *) 0;
}


int main (void)
{
struct entry findEntry (struct entry listPtr, int match);
struct entry n1, n2, n3;
struct entry listPtr, listStart = &n1;


int search;

n1.value = 100;
n1.next = &n2;

n2.value = 200;
n2.next = &n3;

n3.value = 300;
n3.next = 0;
Free download pdf