我正在使用一系列结构来存储n个学生的信息。首先使用qsort()函数对该结构数组进行排序,然后使用bsearch()函数在已排序的结构数组中搜索滚动号。我应该为bsearch()的comparator函数编写什么代码?
源代码:

#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");
}

最佳答案

bsearch()qsort()使用相同的比较函数,但请记住keybsearch()应为struct student。所以你的代码是这样的:

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

最后一件事。切勿使用gets()。始终至少使用fgets()

关于c - C中的bsearch函数和结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52859845/

10-13 06:44