[Solved] Compare function for qsort using two fields of a structure?


Your code as written has several syntax errors, and also your comparison function doesn’t do quite what you want. Quoting from the manpage for qsort:

The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respec‐
tively less than, equal to, or greater than the second. If two mem‐
bers compare as equal, their order in the sorted array is undefined.

Consider the following code:

#include <stdlib.h>
#include <string.h>

struct product {
    char name[30]; 
    float price;
};

int compare(const void *a, const void *b) {

  const struct product *x = a;   // void* can be assigned to any other pointer type
  const struct product *y = b;

  int comp =  x->price - y->price;

  if (comp < 0)
    return -1;

  if (comp > 0)
    return 1;

  comp = strcmp(x->name, y->name);

  return comp;
}

If you want to reverse the sort order, negate comp at the appropriate place.

As others have mentioned, this is C code, and is not idiomatic C++.

2

solved Compare function for qsort using two fields of a structure?