Sorting Structure in C using qsort()

Hi
Can someone please help me out, I’m trying to sort user defined Structure , using predefined function qsort().
I’m getting segmentation fault.

Code : link

There are 2 changes that are needed:

  1. In qsort function call
    qsort(arr, n, sizeof(struct Student ),comparator);

  2. Inside comparator:

    int comparator(const void* p0, const void* p1)
    {
    struct Student* ps0 = (struct Student*) p0;
    struct Student* ps1 = (struct Student*) p1;
    return strcmp( ps0->name, ps1->name);
    }

1 Like

I have looked at your code and there are quite a number of optimisations you can do to make your code more efficient and effective.

  • Replace
struct Student * arr = (struct Student *) malloc(n * sizeof(struct Student));

by

struct Student * arr = malloc(n * sizeof(*arr));

Why? Because you are already storing the return address of malloc() function into a pointer which can extract the value from the address, don’t do double casting.
To know more about it, refer to Do I need to cast the return type of malloc() / calloc()?

  • Replace
qsort(arr, n, sizeof(struct Student *),comparator);

by

qsort(arr, n, sizeof(*arr), comparator);
  • You need to change your comparator() function, it should be:
int comparator(const void* p0, const void* p1) 
{ 
	struct Student *ps0 = (struct Student*) p0;
        struct Student *ps1 = (struct Student*) p1;
        return strcmp( ps0->name, ps1->name);
} 

Whenever working with void* or void pointers a.k.a generic pointers, remember that whenever de-referencing void*, you need to first type-cast into the pointer which can extract the data from the memory location to which the void* is pointing to which in this case is struct Student*.

You can also write your comparator() function like this:

int comparator(const void* p0, const void* p1) 
{ 
	return strcmp(((struct Student*) p0) -> name, ((struct Student *) p1) -> name);
} 

You can check your program with the above changes made from the below links:

  1. Try Online 1!.
  2. Try Online 2!.

Thanks for reading
Peace :v:

2 Likes

Why don’t make use of typedef in your struct and use the given name instead of struct Student all the time.