我在使用一些指针/数组表示法时遇到了问题。我有两个列表,正在对它们进行排序,然后尝试显示它们。关于声明是什么以及为什么,我在下面的代码中有 3 条评论。我的代码如下所示:
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);
}
}
最佳答案
这似乎是家庭作业,所以我会以(希望)引导您朝着正确方向前进的方式回答。
bsearch()
函数在排序列表中搜索 一个 元素,并返回它的位置,或者一个指示符,说明它没有找到。您上面发布的代码似乎以不同的方式使用了 bsearch()
。
考虑单独对待每个注册者,并多次使用 bsearch()
来查看每个注册者是否在与会者列表中。如果不是,则显示注册人姓名。不要忘记 bsearch()
只有在列表已排序时才能正常工作。
关于c - 使用 qsort、bsearch 帮助处理 C 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2304040/