【问题标题】:Sort Addresses in C Program Using Qsort使用 Qsort 在 C 程序中对地址进行排序
【发布时间】:2012-10-18 08:32:13
【问题描述】:

我正在尝试按内存地址对指针数组进行排序:

#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

任何建议将不胜感激!

【问题讨论】:

    标签: c sorting qsort


    【解决方案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;
    }
    

    【讨论】:

      【解决方案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;
      }
      

      但由于指针并非都指向同一个数组(或末尾的一个),因此在技术上这是未定义的行为。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 2010-12-20
        • 1970-01-01
        • 2010-10-21
        • 2019-05-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多