qsort未正确排序指向C中结构的指针数组



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

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

结构

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/%dn",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

感谢你们提前:(

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

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;
}

最新更新