I'm trying to refactor a utility that is currently a stand-alone C program, such that I can make a reusable library. It includes a sorting step of an array, according to the corresponding value within a global array.
// Global lookup table
double *rating;
// Comparator using lookup
int comp_by_rating(const void *a, const void *b) {
int * x = (int *) a;
int * y = (int *) b;
if (rating[*x] > rating[*y])
return 1;
else if (rating[*x] < rating[*y])
return -1;
else
return 0;
}
int main() {
int* myarray;
// ...
// initialize values of local myarray and global rating
// ...
qsort(myarray, length_myarray, sizeof(int), comp_by_rating);
// ...
return 0;
}
Is there a way for me to avoid having the rating
lookup table global? I'm traditionally a C++ person so my first thought was a functor, but I have to stay in C and so I guess I'm functor-less. I also can't replace int *myarray
with an array of structs holding the rating for each item, since other code requires the array in its current form. Do I have any other options?