c - 帮助解决函数中的段错误

标签 c segmentation-fault qsort

一段时间以来,我一直在尝试解决这个 bsearch 作业问题。我尝试使用我的代码首先搜索一个条目,如下所示:

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

char *SearchList(char *key, char *list[], size_t num) 
{
    char **value = bsearch(&key, list, num, sizeof(list[0]), Compare);
    return (value == 0 ? 0 : *value);
}

/*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 = SearchList((char *)registrants[0], (char **)attendees, attendeeCount);
}

我的 missedFirstMeeting 似乎可以正确调用单个值,但是当我尝试在循环中重复调用我的 SearchList 函数时:

for (int i = 0; i < attendeeCount; i++) {
    *missedFirstMeeting = SearchList((char *)registrants[i], (char **)attendees, attendeeCount);
}

我收到段错误。对我来说,我似乎在做同样的事情,但只是重复调用 SearchList(),但显然有些错误我没有看到,因为我收到了段错误。有任何想法吗?谢谢。

最佳答案

删除 firstMeeting 的前导“*”:

missedFirstMeeting = SearchList((char *)registrants[i], (char **)attendees, attendeeCount);

关于c - 帮助解决函数中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2307343/

相关文章:

c - 使用文本文件中的特定字符串与用户输入进行比较

c - 将文件保存到特定线程内的字符串

c - gcc-10.0.1 特定的段错误

c++ - qsort线程安全吗?

c - "d = (((INT32) a) * ((INT32) b))"中的外括号重要吗?

c - C语言中外部变量的使用

c - 解析 C 中的命令行条目 : implementing a shell

c++ - [C++][DPDK] 创建一个正确的 "private size"字节对齐的 rte_mempool

c++ - 使用 qsort 对每个字符串进行排序,然后对字符串集进行排序

c - 解释qsort中的C代码行