【发布时间】:2016-01-15 07:03:31
【问题描述】:
我正在尝试对 C 中的结构数组进行排序 - 我一直在尝试使用 qsort 来执行此操作,但是,每当调用 sorterFunction 时,我都会遇到分段错误。我不确定我在这里做错了什么。
这是我在数组中填充的结构
typedef struct Song
{
char* title;
char* artist;
char* year;
} Song;
这些是排序功能
int comparisonFunction(const void *first, const void *second)
{
Song *songPtr = (Song *)first;
Song *songPtr2 = (Song *)second;
return strcmp(songPtr->title,songPtr2->title);
}
void sorterFunction(Song* songList, int globalCounter)
{
Song newGlobalList[1024];
// the following line is the one that causes segmentation fault
qsort(newGlobalList, globalCounter, sizeof(Song), comparisonFunction);
int count = 0;
while(count < globalCounter)
{
printf("%i Title: %s, Artist: %s, Year: %s\n",count+1,newGlobalList[count].title,newGlobalList[count].artist,newGlobalList[count].year);
count++;
}
}
【问题讨论】:
-
我假设您实际上是在 初始化
newGlobalList数组?但是您甚至需要临时数组吗?因为你展示的结构那么songList不能是链表,而必须是动态分配的数组,也就是说你可以直接使用。 -
我假设
comparisonFunction中的a和b应该是first和second。 -
@MarcKhadpe 正确!试图使代码对 SO 更具可读性,对不起! :-)
-
@JoachimPileborg 是的!你可以假设 newGlobalList 已经被初始化为一个填充结构的数组,很抱歉造成混淆!
-
那么,您正在使用有效指针作为第一个参数调用它吗?有效的
globalCounter值?songList中的每个Song结构都已正确初始化?您可以尝试创建一个Minimal, Complete, and Verifiable Example 并展示给我们吗?