使用qsort,bsearch在C中使用指针的帮助
我在使用一些指针/数组表示法时遇到问题。我有两个列表,正在对它们进行排序,然后尝试显示它们。关于声明是什么以及为什么,我在下面的代码中有3条注释。我的代码如下所示:使用qsort,bsearch在C中使用指针的帮助,c,pointers,qsort,bsearch,C,Pointers,Qsort,Bsearch,我在使用一些指针/数组表示法时遇到问题。我有两个列表,正在对它们进行排序,然后尝试显示它们。关于声明是什么以及为什么,我在下面的代码中有3条注释。我的代码如下所示: int Compare(const void *a, const void *b); void SortStudents(char *studentList[], size_t studentCount) { qsort(studentList, studentCount, sizeof(studentList[0]),
int Compare(const void *a, const void *b);
void SortStudents(char *studentList[], size_t studentCount)
{
qsort(studentList, studentCount, sizeof(studentList[0]), Compare);
}
int Compare(const void *a, const void *b)
{
return (strcmp(*(char **)a, *(char **)b));
}
/*Determines which registrants did not attend the first meeting by searching for registrants
that are not in attendees set. */
void DisplayClassStatus(
const char *registrants[], size_t registrantCount,
const char *attendees[], size_t attendeeCount)
{
char **missedFirstMeeting; // not sure if this is the right declaration
char *start, *end;
// not sure if this is right with the &attendees and registrants for the bsearch()
missedFirstMeeting = bsearch(&attendees, registrants, attendeeCount,
sizeof(attendees[0]), Compare);
printf("Missed First Meeting: \n");
//not sure if this the way to traverse through the array using pointers to display
for (start = missedFirstMeeting, end = &missedFirstMeeting[registrantCount-1]; start < end; ++start) {
printf("%s", *start);
}
}
int比较(const void*a,const void*b);
无效排序学生(字符*studentList[],大小\u t studentCount)
{
qsort(studentList,studentCount,sizeof(studentList[0]),Compare);
}
整数比较(常数无效*a,常数无效*b)
{
返回(strcmp(*(字符**)a,*(字符**)b));
}
/*通过搜索注册人确定哪些注册人没有参加第一次会议
不在与会者集中的*/
无效显示类状态(
常量字符*注册人[],大小和注册人数,
常量字符*与会者[],人数(与会者人数)
{
char**missedFirstMeeting;//不确定这是否是正确的声明
字符*开始,*结束;
//不确定这是否适用于&b研究()的与会者和注册人
missedFirstMeeting=b搜索(&A)与会者、注册人、与会者人数,
sizeof(与会者[0]),比较;
printf(“错过的第一次会议:\n”);
//不确定这是否是使用指针来显示的遍历数组的方法
对于(开始=missedFirstMeeting,结束=&missedFirstMeeting[RegintCount-1];开始<结束;++开始){
printf(“%s”,*开始);
}
}
这似乎是家庭作业,因此我将以这样一种方式回答(希望)引导您走向正确的方向
bsearch()
函数在已排序的列表中搜索一个元素,并返回其位置或表示未找到该元素的指示符。上面发布的代码似乎以不同的方式使用了bsearch()
考虑单独对待每个注册人,并多次使用bsearch()
查看每个注册人是否在与会者列表中。如果没有,则显示注册人的姓名。不要忘记,只有在列表已排序的情况下,bsearch()
才能正常工作