0

I'm trying to sort an array of structs in C - I've been trying to use qsort to do this, however, whenever the sorterFunction is called, I get a segmentation fault. I'm not exactly sure what I'm doing wrong here.

This is the struct I have populated my array with

typedef struct Song 
{
    char* title;
    char* artist;
    char* year; 
} Song;

These are the sorting function

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++;
        }
    }
6
  • 2
    I assume you are actually initializing the newGlobalList array? But do you even need the temporary array? Because with the structure you show then songList can't be a linked list, but must be a dynamically allocated array, which means you can use it directly. Commented Jan 15, 2016 at 7:05
  • 1
    I assume a and b in the comparisonFunction should be first and second. Commented Jan 15, 2016 at 7:07
  • @MarcKhadpe Correct! Was trying to make the code more readable for SO, sorry! :-) Commented Jan 15, 2016 at 7:08
  • @JoachimPileborg Yes! You can assume that newGlobalList is already initialized as an array of populated structs, sorry for the confusion! Commented Jan 15, 2016 at 7:10
  • 1
    Then, you are calling it with a valid pointer as the first argument? A valid globalCounter value? Each Song structure in songList is properly initialized? Can you please try to create a Minimal, Complete, and Verifiable Example and show us? Commented Jan 15, 2016 at 7:14

1 Answer 1

1

Firstly, your size of array is globalCounter, but not 1024, as specified above.

Secondly, you are missing initialization of songs structs. Thats why inner pointers char * title are invalid. You get segfault because of strcmping invalid pointers

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I didn't realize I was using qsort incorrectly! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.