I am trying to sort an array of pointers by the memory address:
#include <stdio.h>
#include <stdlib.h>
typedef struct flist {
int size;
struct flist *blink;
struct flist *flink;
} *Flist;
int compare(const void *x, const void *y)
{
Flist a = (Flist)x;
Flist b = (Flist)y;
if(a < b)
return -1;
else
return 1;
}
int main()
{
int a[] = {3, 1, 2, 4, 0};
Flist b[5];
int i;
for(i = 0; i < 5; i++)
b[a[i]] = (Flist)malloc(12);
printf("Here is the array before sorting:\n");
for(i = 0; i < 5; i++)
printf("%p\n", b[i]);
qsort(b, 5, sizeof(Flist), compare);
printf("Here is the array after sorting:\n");
for(i = 0; i < 5; i++)
printf("%p\n", b[i]);
}
However, the program has no effect on the order of the addresses:
Here is the array before sorting:
0x759090
0x759030
0x759050
0x759010
0x759070
Here is the array after sorting:
0x759090
0x759030
0x759050
0x759010
0x759070
Any suggestions would be much appreciated!
You are missing a level of indirection: qsort
sends in addresses of elements being sorted, not the elements themselves.
In your case, you are seeing addresses of the addresses of your Flist
elements being passed. You need to dereference the pointers passed in after casting to Flist*
(which is a pointer to a pointer):
int compare(const void *x, const void *y) {
Flist a = *((Flist*)x);
Flist b = *((Flist*)y);
if(a < b)
return -1;
else
return 1;
}