c - C中的bsearch函数和结构
问题描述
我正在使用一组结构来存储 n 个学生的信息。这个结构数组首先使用 qsort() 函数进行排序,然后使用 bsearch() 函数在排序的结构数组中搜索卷号。我应该为 bsearch() 的比较器函数编写什么代码?
源代码:
#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");
}
解决方案
推荐阅读
- sml - ML中的AVL树-向左旋转,警告:匹配非穷举
- windows - Spring Boot 应用程序在 Windows 10 上启动,但在 OS X (HS) 上不启动
- php - 将变量返回到视图
- reactjs - React-bootstrap:一行中的两列未呈现
- python - 从 beautifulsoup 结果中删除HTML 标记
- css - Bootstrap 3输入组插件丢失标记
- r - R:如何以递归方式将文本文件读入列表列表?
- php - 在 symfony4 中为 redis 设置无键前缀
- firebase - 如何使用 firebase cli 将文件推送到 firebase 存储
- swift - 部分中选定行的索引