[英]bsearch function and structure in C
我正在使用结构数组来存储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");
}
对bsearch()
和qsort()
使用相同的比较函数,但请记住bsearch()
的key
应为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()
。
bsearch
页提供了一个不错的例子。 您必须对qsort
和bsearch
使用相同的比较功能,因为bsearch
假定一个已排序的列表,并使用其比较功能来确定其迭代搜索过程中下一个搜索的方向。
乍一看,我认为您不需要重新定义比较功能。 您应该能够对qsort
和bsearch
都使用compare
,实际上,如果bsearch
要成功搜索qsort
顺序,则这些功能必须等效。
通过首先形成struct student
并使用其.id
成员,代码可以使用与qsort()
使用的比较函数相同的比较函数。
struct student dummy;
dummy.id = key;
struct student *res = bsearch(&dummy, S, SIZE, sizeof S[0], compare1);
另外,代码可以使用其他比较并直接使用int key
。
int bsearch_compare(const void* key_ptr, const void* element_ptr){
int id1 = *((const int *)key_ptr);
int id2 = ((const struct student *)element_ptr)->id;
return id1 - id2;
}
struct student *res = bsearch(&key, S, SIZE, sizeof S[0], bsearch_compare);
为了获得正确的全范围int
功能,请同时更改两个比较功能:
// return id1 - id2;
return (id1 > id2) - (id1 < id2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.