c - 使用 qsort、bsearch 帮助处理 C 中的指针

标签 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]), 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/

相关文章:

c - 使用 C 中的 strtok 解析配置中的字符串

c - 使用链表实现堆栈的意外结果

c - printf ("%p"int 1) 是什么意思?

c - 使用 qsort() 对整数数组进行排序并交换字符串

c - 如何将 char * 放入数组中,以便我可以在 qsort 中使用它,然后转到下一行

c - osx - 在分配的内存页上写入和执行

c++ - 如何在 addr2line 运行时从偏移量中的 backtrace_symbols() 解析 cpp 符号

c - 使用 scanf 读取空格分隔的数字并将它们存储在数组中 - C

c - C指针指的是物理地址还是虚拟地址

c++ - 对定义为 vector<double> 的矩阵进行排序