C语言bsearch、qsort

可以bsearch 结构体的成员
https://stackoverflow.com/questions/52859845/bsearch-function-and-structure-in-c

#include<stdio.h>
#define SIZE 15

// search for a structure in array of structures using qsort() and bsearch()

struct student{
    int id;
    char name[30];
}S[SIZE];

int compare(const void* S, const void* T){
    int id1 = ((struct student *)S) -> id;
    int id2 = ((struct student *)T) -> id;

    return id1 - id2;
}

struct student comapre1(const void* S, const void* T){
    // what code should i include here
}

void main(){
    int size, i;
    printf("How many students are there ?: ");
    scanf("%d", &size);
    printf("----------------------------------------------------------\n");

    for(i = 0 ; i < size ; i++){
        printf("Student %d\nEnter roll number: ",i+1);
        scanf("%d", &S[i].id);
        while(getchar() != '\n');
        printf("Enter name: ");
        gets(S[i].name);
        printf("----------------------------------------------------------\n");
    }

    qsort(S, SIZE, sizeof(struct student), compare);        // sorting array of structues

    int key;    // roll number to be searched

    printf("Enter roll number whose record wants to be searched: ");
    scanf("%d", &key);

    struct student *res = bsearch(&key, S, SIZE, sizeof(struct student), compare1);

    if(res != NULL){    
        // display name and id of record found
    }else
        printf("not found");
}


Use same compare function for both bsearch() and qsort(), but remember that the key for bsearch() should be as struct student. So your code will be like this:

struct student student_key;    // roll number to be searched

printf("Enter roll number whose record wants to be searched: ");
scanf("%d", &(student_key.id));

struct student *res = (struct student *)bsearch(&student_key, S, size, sizeof(struct student), compare)
posted @ 2022-06-13 23:41  Atituiset  阅读(118)  评论(0)    收藏  举报