【问题标题】:Sorting Elements in Struct Array in C在 C 中对结构数组中的元素进行排序
【发布时间】: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 中的ab 应该是firstsecond
  • @MarcKhadpe 正确!试图使代码对 SO 更具可读性,对不起! :-)
  • @JoachimPileborg 是的!你可以假设 newGlobalList 已经被初始化为一个填充结构的数组,很抱歉造成混淆!
  • 那么,您正在使用有效指针作为第一个参数调用它吗?有效的globalCounter 值? songList 中的每个 Song 结构都已正确初始化?您可以尝试创建一个Minimal, Complete, and Verifiable Example 并展示给我们吗?

标签: c arrays sorting struct


【解决方案1】:

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

其次,您缺少歌曲结构的初始化。这就是为什么内部指针char * title 无效的原因。由于strcmping 无效指针,您会遇到段错误

【讨论】:

  • 谢谢!我没有意识到我错误地使用了 qsort! :-)
猜你喜欢
  • 1970-01-01
  • 2014-01-13
  • 2011-05-13
  • 2014-03-12
  • 2016-07-14
  • 1970-01-01
相关资源
最近更新 更多