![]() |
![]() |
![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
![]() |
![]() |
[an error occurred while processing this directive]
Steps
How It Works Lets look at MAIN.CPP. The first step is to define the appropriate version of compare, the callback function used by _lsearch. int __cdecl compare (const void* pfirst, const void * psecond) /* callback function */ { return (*(const char *) pfirst) - (*(const char *) psecond); } An array of two characters is defined and initialized inside main(). Also define two keys to be looked up in the array, a void pointer to store the result of _lsearch, and an unsigned int that holds the number of array elements. char arr[] = {a, b};/* define and initialize an array of 2 chars */ char key = a; char key2 = c; /* false key which does not exist in arr */ void *p = NULL; /* store the result of _lsearch */ unsigned int num = 2; /* number of elements in arr */ _lsearch is invoked with the key a. This value exists in the array, so _lsearch returns a pointer to the address of the array element that holds the value a. /*first invocation. _lsearch finds a in arr */ p = _lsearch( &key, /* address of key */ arr, /* address of arrays beginning */ &num, /* number of elements in array */ sizeof (char), /* sizeof each element */ compare); /* pointer to user-defined comparison function */ if (p) printf(%c was found!\n, *(char*)p); The second invocation of _lsearch looks up the value c in the array. This value does not exist in arr. Therefore, _lsearch appends c to the end of the array, increments num, and returns a pointer to the newly added element: /* second invocation. _lsearch cant find c in arr */ /* c is appended to arr and num incremented */ p = _lsearch( &key2, /* address of key */ arr, /* address of arrays beginning */ &num, /* number of elements in array */ sizeof (char), /* sizeof each element */ compare); /* pointer to user-defined comparison function */ printf(%c was appended to arr\n, * (char*) p ); printf(arr has %d elements \n, num ); printf(the newly added element is: %c\n, arr[2] ); } Comments When can _lsearch be useful? Suppose you need to compile a thesaurus of words that appear in some document. This process can be streamlined by using _lsearch. First, you declare an array of char *, in which every element represents a word. Then you retrieve the next word from the document and use _lsearch to look it up in the current array. If _lsearch doesnt find the word, it appends the missing word to the end of the array. This process is repeated until the entire document has been read. The resultant array contains all the words of the document.
|
![]() |
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.
|