gpt4 book ai didi

c - 使用 qsort 函数对结构进行排序

转载 作者:行者123 更新时间:2023-12-04 19:07:14 24 4
gpt4 key购买 nike

所以我需要使用 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);
}

我正在尝试获取输出:
1 
3
10
但相反,我得到了一个段错误核心转储。
这里有什么问题?

最佳答案

在取消引用指针之前,您必须将指针分配给有效缓冲区。
在这种情况下,working应该是结构数组,而不是指针数组。
也不要忘记初始化所有要排序的元素。
您的代码中还有更多错误:

  • qsort使用时不包含正确的标题 ( stdlib.h )
  • 未申报 compareEncounters用于main功能。
  • printf() 后面缺少分号陈述。
  • 未申报 bc用于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].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);
    }

    关于c - 使用 qsort 函数对结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66034501/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com