I have a question regarding qsort.
This is a bit strange, but my qsort function does not give me the correct result. Itβs strange that some of my comparison functions are identical to my past projects, but they donβt give me the correct input at all. I'm not sure how to test it.
For instance:
int comp_name_asc(const void *a, const void *b) { const Rec *prec1 = (const Rec *) a; const Rec *prec2 = (const Rec *) b; return strcmp(prec1->name, prec2->name); } int comp_name_desc(const void *a, const void *b) { const Rec *prec1 = (const Rec *) a; const Rec *prec2 = (const Rec *) b; return strcmp(prec2->name, prec1->name); }
The second function should be decreasing, but the result is identical: it is always in ascending order. I checked that the correct function was introduced at the right time. Rec is a typedef for the structure I created that has a char * parameter for the name.
Also (EDIT to avoid overflow):
int comp_size_asc(const void *a, const void *b) { const Rec *prec1 = (const Rec *) a; const Rec *prec2 = (const Rec *) b; if (prec1->byteSize > prec2->byteSize) return 1; else if (prec1->byteSize < prec2->byteSize) return -1; else return 0; }
The result is completely strange, not upward or downward (i.e.: 500, 515, 100, 200 ...). byteSize is of type off_t, obtained:
char *path;
I'm really not sure how to debug this. All I know is that the corresponding comparison function is introduced, and that some similar comparison functions are used to work in the past.
Any ideas or how I can debug this is welcome. Thanks.
EDIT:
Adding a call to qsort:
int index = 0; Rec **array = (Rec **) malloc(sizeof(Rec *) * capacity);
(Each time an element is added to an array, the index increases.)
Thanks.
EDIT:
The solution was given below. Thanks!
I had to change:
const Rec *prec1 = (const Rec *) a;
to
const Rec *prec1 = *(const Rec **) a;
due to the way i defined my array. Thanks!