home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / vc98 / crt / src / lsearch.c < prev    next >
C/C++ Source or Header  |  1998-06-17  |  2KB  |  68 lines

  1. /***
  2. *lsearch.c - linear search of an array
  3. *
  4. *       Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
  5. *
  6. *Purpose:
  7. *       contains the _lsearch() function - linear search of an array
  8. *
  9. *******************************************************************************/
  10.  
  11. #include <cruntime.h>
  12. #include <stddef.h>
  13. #include <search.h>
  14. #include <memory.h>
  15.  
  16. /***
  17. *char *_lsearch(key, base, num, width, compare) - do a linear search
  18. *
  19. *Purpose:
  20. *       Performs a linear search on the array, looking for the value key
  21. *       in an array of num elements of width bytes in size.  Returns
  22. *       a pointer to the array value if found; otherwise adds the
  23. *       key to the end of the list.
  24. *
  25. *Entry:
  26. *       char *key - key to search for
  27. *       char *base - base of array to search
  28. *       unsigned *num - number of elements in array
  29. *       int width - number of bytes in each array element
  30. *       int (*compare)() - pointer to function that compares two
  31. *               array values, returning 0 if they are equal and non-0
  32. *               if they are different. Two pointers to array elements
  33. *               are passed to this function.
  34. *
  35. *Exit:
  36. *       if key found:
  37. *               returns pointer to array element
  38. *       if key not found:
  39. *               adds the key to the end of the list, and increments
  40. *               *num.
  41. *               returns pointer to new element.
  42. *
  43. *Exceptions:
  44. *
  45. *******************************************************************************/
  46.  
  47. void * __cdecl _lsearch (
  48.         REG2 const void *key,
  49.         REG1 void *base,
  50.         REG3 unsigned int *num,
  51.         unsigned int width,
  52.         int (__cdecl *compare)(const void *, const void *)
  53.         )
  54. {
  55.         unsigned int place = 0;
  56.         while (place < *num )
  57.                 if (!(*compare)(key,base))
  58.                         return(base);
  59.                 else
  60.                 {
  61.                         base = (char *)base + width;
  62.                         place++;
  63.                 }
  64.         (void) memcpy( base, key, width );
  65.         (*num)++;
  66.         return( base );
  67. }
  68.