2012-10-29 27 views
1

我想排序的内存地址的指针数组:排序地址使用的qsort

#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]); 
} 

然而,该方案具有地址的顺序没有任何影响:

这里是分选前的阵列:
0x759090
0x759030
0x759050
0x759010
0x759070
这里是数组排序后:
0x759090
0x759030
0x759050
0x759010
0x759070

任何建议,将不胜感激!

回答

1

您错过了一个间接级别:qsort发送地址的元素被排序,而不是元素本身。

在你的情况,你看到你的Flist元素的地址的地址传递。您需要取消引用铸造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; 
} 
+0

哇,谢谢!我感谢帮助! – user434462

2

compare接收阵列元件的地址。这些当然已经是按顺序。

要由值进行排序,你需要改变compare

int compare(const void *x, const void *y) 
{ 
    Flist a = *(Flist*)x; 
    Flist b = *(Flist*)y; 

    if(a < b) 
     return -1; 
    else if (a == b) 
     return 0; 
    else 
     return 1; 
} 

但由于指针不都指向同一数组(或一个过去的结束),它在技术上未定义的行为。

+0

谢谢,这有助于澄清一些事情! – user434462