Tool/software: Code Composer Studio
I add test code in tivxDmpacSdeCreate() fuction, after qsort() I print the result, but is not right, the right order is 10, 7, 5, 3, 1.
Could you help me to find out why qsort() is wrong?
Thanks & Regards,
Li
This thread has been locked.
If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.
Tool/software: Code Composer Studio
I add test code in tivxDmpacSdeCreate() fuction, after qsort() I print the result, but is not right, the right order is 10, 7, 5, 3, 1.
Could you help me to find out why qsort() is wrong?
Thanks & Regards,
Li
The compare function needs to return:
Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):
return value | meaning |
---|---|
<0 |
The element pointed to by p1 goes before the element pointed to by p2 |
0 |
The element pointed to by p1 is equivalent to the element pointed to by p2 |
>0 |
The element pointed to by p1 goes after the element pointed to by p2 |
Your compare function never returns a negative number. Read the docs!
The documentation for the qsort comparison function is:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined.
Whereas your compare_res function returns:
Try the following compare_res function:
int compare_res(const void *a, const void *const b) { const uint32_t *pa = a; const uint32_t *pb = b; if (*pa < *pb) { return -1; } else if (*pa == *pb) { return 0; } else { return 1; } }
Keith, it is avoid a warning because the data to the qsort comparison function is const-qualified.Keith Barkley said:Why did you make pa and pb const?
With the TI ARM v20.2.1 compiler the following is warning free:
int compare_res_const(const void *a, const void *b) { const uint32_t *pa = a; const uint32_t *pb = b; if (*pa < *pb) { return -1; } else if (*pa == *pb) { return 0; } else { return 1; } }
Whereas the following produces warnings:
int compare_res_no_const(const void *a, const void *b) { uint32_t *pa = a; uint32_t *pb = b; if (*pa < *pb) { return -1; } else if (*pa == *pb) { return 0; } else { return 1; } }
"../main.c", line 62: warning #145-D: a value of type "const void *" cannot be used to initialize an entity of type "uint32_t *" uint32_t *pa = a; ^ "../main.c", line 63: warning #145-D: a value of type "const void *" cannot be used to initialize an entity of type "uint32_t *" uint32_t *pb = b; ^