0
votes

I have a comparator function that returns 1, 0, or -1, declared as follows:

int multiPrecisionCompare(const DIGIT_T a[], const DIGIT_T b[], int32_t length); 

where DIGIT_T is int8_t.

I want to call a function qsort but I have a problem understanding what I have to change or how to call the comparator function inside.

qsort(bigArray->x, 8,30 , <-what here?????->);


    i

int multiprecisionCompare(const DIGIT_T a[], const DIGIT_T b[], int32t length) 
{
  while(length--) { // little endian
if(a[length] > b[length])
  return 1;
if(a[length] < b[length])
  return -1;
}

return 0;
}


point * bigArray = (point *)(malloc(K*sizeof(point)));
CreateListAndOrder( lots of parameters) // this fills the bigArray unsorted
/* point is a structure of X,Y,Z where each of this is DIGIT_T */
qsort((void *)bigArray, K, sizeof(point), cmp);

I want to sort it according to X coordinate, but that is solved by int32t length, that it should compare only first coordinate from that struct

int cmp(const void *a, const void *b){
    return multiPrecisionCompare((const DIGIT_T*)a, (const DIGIT_T*)b,  DIGIT_LENGTH);
    //return multiPrecisionCompare(*(const DIGIT_T**)a, *(const DIGIT_T**)b,  DIGIT_LENGTH);
}
3
struct data { DIGIT_T *n; int32_t length; };.. int multiPrecisionCompare(const struct data *a, const struct data *b); or length pass to compare function by Global variable.BLUEPIXY
Does your compiler support qsort_s(base, nmemb, size, compar, context);?chux - Reinstate Monica
Show point. maybe return multiPrecisionCompare(((point*)a)->x, ((point*)b)->x, DIGIT_LENGTH);BLUEPIXY
typedef struct { DIGIT_T x[length]; DIGIT_T y[length]; DIGIT_T z[length]; } point; length is defined as constant number. I have tried the latest change but it is still comparing the addresses not the valuesuser3411282

3 Answers

2
votes

qsort accepts a pointer to a function with the following signature:

int cmp(void const *, void const *)

You have to adjust your comparison function, to match this signature, and than simply pass in a function pointer.

1
votes

Here is an example:

int cmpfunc (const void * a, const void * b)
{
   return ( *(DIGIT_T *)a - *(DIGIT_T *)b );
}

qsort(bigArray->x, 8, 30 , cmpfunc);
1
votes
int multiPrecisionCompare(const DIGIT_T a[], const DIGIT_T b[], int32_t length);
int32_t DIGIT_LENGTH;
int cmp(const void *a, const void *b){
    return multiPrecisionCompare(((point*)a)->x, ((point*)b)->x, DIGIT_LENGTH);
}

DIGIT_LENGTH = length;
point * bigArray = (point *)malloc(K*sizeof(point));
//fills the bigArray unsorted
qsort(bigArray, K, sizeof(point), cmp);