我正在尝试对 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++;
}
}
最佳答案
首先,您的数组大小是 globalCounter
,但不是上面指定的 1024
。
其次,您缺少歌曲结构的初始化。这就是内部指针 char * title
无效的原因。由于 strcmp
ing 无效指针
关于c - 在 C 中对结构体数组中的元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34805822/