Advertisement
Guest User

Untitled

a guest
May 26th, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. //
  2. // minElement.c
  3. // minElement
  4. //
  5. // Created by Saibhan on 4/16/15.
  6. // Copyright (c) 2015 Saibhan. All rights reserved.
  7. //
  8.  
  9. #include <stdio.h>
  10. #include <string.h>
  11.  
  12. void *minElement(void *beg, void *end, size_t size, int (*cmp)(void *s, void *q))
  13. {
  14. void *res = beg;
  15. char *cur = beg;
  16. if (cur != end)
  17. {
  18. cur += size;
  19.  
  20. while (cur != end)
  21. {
  22. if (cmp(res, cur) > 0)
  23. {
  24. res = cur;
  25. }
  26. cur += size;
  27. }
  28. }
  29. return res;
  30. }
  31.  
  32. int cmpChar(void* p, void* q)
  33. {
  34. return *((char *)p) - *((char *)q); // *((char *)p) casting to type pointer to character then we dereference it to 1 byte
  35. }
  36.  
  37. int cmpInt(void* p, void* q)
  38. {
  39. return *((int *)p) - *((int *)q); // *((char *)p) casting to type pointer to character then we dereference it to 1 byte
  40. }
  41.  
  42. int cmpStr(void* p, void* q)
  43. {
  44. return strcmp(*(char**)p, *(char**)q);
  45. }
  46.  
  47. int main(void)
  48. {
  49. char a1[] = {'a', '0', '1'};
  50. int a2[] = {1, 11, 5};
  51. char* a3[] = {"Java", "C", "C++"};
  52.  
  53. char* pCharMin = (char *)minElement(a1, a1 + 3, sizeof(char), cmpChar);
  54. int* pIntMin = (int *)minElement(a2, a2 + 3, sizeof(int), cmpInt);
  55. char** pStrMin = (char **)minElement(a3, a3 + 3, sizeof(char*), cmpStr);
  56.  
  57. printf("%c\n", *pCharMin);
  58. printf("%d\n", *pIntMin);
  59. printf("%s\n", *pStrMin);
  60.  
  61. return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement