I have a problem in qsort(arr, n, sizeof(int), compare)
here how the compare calls its parameter. As I known its a void pointer and it calls the address of the array element and then it compares the value. But how it known the order of array element.
I also attached the whole code and function definition.
#include <stdio.h>
#include <stdlib.h>
int compare(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main ()
{
int arr[] = {10, 5, 15, 12, 90, 80};
int n = sizeof(arr)/sizeof(arr[0]), i;
qsort (arr, n, sizeof(int), compare);
for (i=0; i<n; i++)
printf ("%d ", arr[i]);
return 0;
}
something like this
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)){
char *ptr1, *ptr2;
int j, i;
for (j = 0 ; j < nitems ; j++){
ptr1 = ((char*) base) + (j * size);
for( i = 0 ; i < nitems ; i++){
ptr2 = ((char*) base) + (i * size);
if( compar(ptr1, ptr2)) {
...
}
}
}
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.