繁体   English   中英

使用 qsort function 对结构进行排序

[英]using qsort function to sort a struct

所以我需要使用 qsort() 对包含结构的数组进行排序

#include <stdio.h>

// =========
struct pair
{
    int encounters;
};// pair{}

int compaireEncounters(const void*, const void*);

int main()
{
    struct pair* working[5];
    working[0]->encounters = 10;
    working[1]->encounters = 3;
    working[2]->encounters = 1;

    qsort(working, 5, sizeof(struct pair), compareEncounters);
    int i = 0;
    while (i < 3)
    {
        printf("%d \n", working[i]->encounters)
        i++;
    }

}

int compaireEncounters(const void* av, const void* bv)
{
    int a = ((struct pair*)av)->encounters;
    int b = ((struct pair*)bc)->encounters;
    return(a > b);
}

我正在尝试获取 output:

1 
3
10

但相反,我得到了一个分段错误核心转储。

这里有什么问题?

在取消引用指针之前,您必须将指针分配给有效缓冲区。

在这种情况下, working应该是结构数组,而不是指针数组。

也不要忘记初始化所有要排序的元素。

您的代码中还有更多错误:

  • 使用qsort时不包括正确的 header ( stdlib.h )
  • 未声明的compareEncounters用于main function。
  • printf()语句后缺少分号。
  • 未声明的bc用于compaireEncounters function。

固定代码:

#include <stdio.h>
#include <stdlib.h>

// =========
struct pair{
    int encounters;
};// pair{}

int compaireEncounters(const void* , const void*);

int main() {
    struct pair working[5];
    working[0].encounters = 10;
    working[1].encounters = 3;
    working[2].encounters = 1;
    working[3].encounters = 334;
    working[4].encounters = 42;

    qsort(working, 5, sizeof(struct pair), compaireEncounters);
    int i = 0;
    while (i < 3) {
        printf("%d \n", working[i].encounters);
        i++;
    }

}

int compaireEncounters(const void* av, const void* bv){
    int a = ((struct pair*)av)->encounters;
    int b = ((struct pair*)bv)->encounters;
    return(a > b);
}

如果要使用指针数组,

  • 在取消引用之前分配缓冲区并分配它们。
  • 修复qsort()的元素大小。
  • 修复compaireEncounters以比较指向结构的指针。
#include <stdio.h>
#include <stdlib.h>

// =========
struct pair{
    int encounters;
};// pair{}

int compaireEncounters(const void* , const void*);

int main() {
    struct pair* working[5];
    working[0] = malloc(sizeof(*working[0])); working[0]->encounters = 10;
    working[1] = malloc(sizeof(*working[1])); working[1]->encounters = 3;
    working[2] = malloc(sizeof(*working[2])); working[2]->encounters = 1;
    working[3] = malloc(sizeof(*working[3])); working[3]->encounters = 334;
    working[4] = malloc(sizeof(*working[4])); working[4]->encounters = 42;

    qsort(working, 5, sizeof(*working), compaireEncounters);
    int i = 0;
    while (i < 3) {
        printf("%d \n", working[i]->encounters);
        i++;
    }

}

int compaireEncounters(const void* av, const void* bv){
    int a = (*(struct pair**)av)->encounters;
    int b = (*(struct pair**)bv)->encounters;
    return(a > b);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM