Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // minElement.c
- // minElement
- //
- // Created by Saibhan on 4/16/15.
- // Copyright (c) 2015 Saibhan. All rights reserved.
- //
- #include <stdio.h>
- #include <string.h>
- void *minElement(void *beg, void *end, size_t size, int (*cmp)(void *s, void *q))
- {
- void *res = beg;
- char *cur = beg;
- if (cur != end)
- {
- cur += size;
- while (cur != end)
- {
- if (cmp(res, cur) > 0)
- {
- res = cur;
- }
- cur += size;
- }
- }
- return res;
- }
- int cmpChar(void* p, void* q)
- {
- return *((char *)p) - *((char *)q); // *((char *)p) casting to type pointer to character then we dereference it to 1 byte
- }
- int cmpInt(void* p, void* q)
- {
- return *((int *)p) - *((int *)q); // *((char *)p) casting to type pointer to character then we dereference it to 1 byte
- }
- int cmpStr(void* p, void* q)
- {
- return strcmp(*(char**)p, *(char**)q);
- }
- int main(void)
- {
- char a1[] = {'a', '0', '1'};
- int a2[] = {1, 11, 5};
- char* a3[] = {"Java", "C", "C++"};
- char* pCharMin = (char *)minElement(a1, a1 + 3, sizeof(char), cmpChar);
- int* pIntMin = (int *)minElement(a2, a2 + 3, sizeof(int), cmpInt);
- char** pStrMin = (char **)minElement(a3, a3 + 3, sizeof(char*), cmpStr);
- printf("%c\n", *pCharMin);
- printf("%d\n", *pIntMin);
- printf("%s\n", *pStrMin);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement