samedi 10 avril 2021

Function that returns max element of an array of different types

I have couple of compare function that go something like this:

int greater_than_int(const void *a, const void *b) {
    if (*(int *)a > *(int *)b) return 1;
    return 0;
}

and a max function that goes like this:

const void* max(const void *base, size_t members, size_t size,
              int (*compar)(const void *, const void *)) {

    int i;
    int n = nmemb / size;
    char *base_ptr = (char *) base;
    char* max = base_ptr;
    for(i = 0; i < n; i++) {
        if (compar((base_ptr + i*size), max) != 0) { 
            *max = *(base_ptr + i*size);
        }
    }
    return max;
}

When I try to run this function with greater_than_int I get nonsense results and since I'm still pretty new with C++ I'm not sure why. Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire