在C中对Struct Array中的元素进行排序

时间:2016-01-15 07:03:31

标签: c arrays sorting struct

我试图在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++;
        }
    }

1 个答案:

答案 0 :(得分:1)

首先,您的数组大小为globalCounter,但不是1024,如上所述。

其次,您缺少歌曲结构的初始化。这就是内部指针char * title无效的原因。由于strcmp无效指针

,您会遇到段错误