【问题标题】:Help with pointers in C using qsort, bsearch使用 qsort、bsearch 帮助 C 中的指针
【发布时间】:2010-02-20 22:44:51
【问题描述】:

我在使用某些指针/数组表示法时遇到问题。我有两个列表并正在对它们进行排序,然后尝试显示它们。我在下面的代码中有 3 cmets 关于声明是什么以及为什么。我的代码如下所示:

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);
    }
}

【问题讨论】:

    标签: c pointers qsort bsearch


    【解决方案1】:

    这似乎是家庭作业,所以我会以(希望)引导您正确方向的方式回答。

    bsearch() 函数在排序列表中搜索 一个 元素,并返回其位置或表示未找到的指示符。您上面发布的代码似乎以不同的方式使用bsearch()

    考虑单独对待每个注册者,并多次使用bsearch() 来查看每个注册者是否在与会者列表中。如果没有,则显示注册人姓名。不要忘记bsearch() 只有在列表排序后才能正常工作。

    【讨论】:

      猜你喜欢
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 2013-12-13
      • 1970-01-01
      相关资源
      最近更新 更多