c - 在 C 中对结构体数组中的元素进行排序

标签 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++;
        }
    }

最佳答案

首先,您的数组大小是 globalCounter,但不是上面指定的 1024

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

,您会出现段错误

关于c - 在 C 中对结构体数组中的元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34805822/

相关文章:

c - 查找数组的起始地址

c - 指向变量与数组的外部指针

C、统计字符串数组中的唯一字符串

python - 如何在使用numpy分区排序后获取数组中 float 的索引

java - 如何更改我的代码以每次在新行上打印出来?

c - 定义返回函数指针的函数有哪些不同风格

c - malloc 和 realloc 段错误

Javascript:仅当它是文本的第一个单词时才替换 'x',而不是其他任何地方

c++ - 知道最小值在数组c++中的位置的最简单方法

java - 如何通过存储在另一个列表中的索引值对一个列表进行排序