【问题标题】:qsort not properly sorting array of pointers to struct in Cqsort 没有正确排序指向 C 中结构的指针数组
【发布时间】:2021-09-20 23:04:54
【问题描述】:

我正在尝试使用 qsort 按其中一个值对指向 struct 的指针数组进行排序。

任何帮助将不胜感激,因为我无法弄清楚为什么这不起作用。比较函数对我来说似乎是正确的,我想知道无符号整数是否有问题。

结构

typedef struct node{

    unsigned int identifier;
    unsigned int value;

}Node;

比较功能

int compare(const void* a, const void* b){
    
    Node* sum_a = (Node*)a;
    Node* sum_b = (Node*)b;
    if(sum_a->value > sum_b->value)return 1;
    if(sum_a->value == sum_b->value)return 0;
    return -1;
}

我用来重现问题的代码

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#define SIZE 20
Node* init_node(Node* ins_node,unsigned int identifier,unsigned int value){
    ins_node = (Node*)malloc(sizeof(Node));
    ins_node->identifier=identifier;
    ins_node->value=value;
    return ins_node;
}
int main (){

    Node*curr_node;
    Node*box[SIZE];
    box[0]=init_node(curr_node,27,9999);
    for(int i = 1;i<SIZE;i++){
        box[i]=init_node(curr_node,i,SIZE*2-i);
    }

    qsort(box,SIZE,sizeof(Node*),compare);

    printf("\nsorted:\n");
    for(int i = 0;i<SIZE;i++){
        printf("%d/%d\n",box[i]->identifier,box[i]->value);
    }
    
}

明显没有排序的输出

sorted:
27/9999
1/39
2/38
3/37
4/36
5/35
6/34
7/33
8/32
9/31
10/30
11/29
12/28
13/27
14/26
15/25
16/24
17/23
18/22
19/21

提前谢谢大家:)

【问题讨论】:

  • 是的。它按值的降序排列。大的先于小的。反转比较函数中的return 1return -1 以按升序排序。 ;)
  • @enhzflep 不是。你看到的降序是由我使用的测试用例的定义给出的,如果你交换返回的输出是相同的。对不起,误导性的测试用例:)
  • 9999, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21 - 你说那我。哪个不正常?!最初的订单是什么?

标签: c sorting pointers pass-by-reference qsort


【解决方案1】:

比较函数无效并调用未定义的行为。数组的元素通过引用传递给函数。所以你至少需要像这样定义函数

int compare(const void* a, const void* b){
    
    Node* sum_a = *(Node**)a;
    Node* sum_b = *(Node**)b;
    if(sum_a->value > sum_b->value)return 1;
    if(sum_a->value == sum_b->value)return 0;
    return -1;
}

函数init_node的第一个参数也没有使用。

定义函数

Node* init_node(unsigned int identifier,unsigned int value){
    Node *ins_node = (Node*)malloc(sizeof(Node));
    ins_node->identifier=identifier;
    ins_node->value=value;
    return ins_node;
}

【讨论】:

  • 谢谢,这解决了我的问题:) 请问为什么(Node*)a 不起作用而*(Node**)a 起作用?
  • @MrCont 数组的元素具有指针类型 Node *。它们通过引用传递给比较函数,例如 &box[i]。所以传递给函数表达式的类型是Node * *。
猜你喜欢
  • 1970-01-01
  • 2015-12-13
  • 2019-01-18
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
相关资源
最近更新 更多