0

I am currently looking into sorting a struct array by a particular field within the structs using the qsort function, but I could use a starting point.

Here is my current struct array:

/* database struct */
typedef struct node {
    char       name[MAX];
    char       lname[MAX];
    char       address[MAX];
    char       number[MAX];
}record_type;

/* global variables */
record_type record[100];

I would like to be able to sort this by the "name" field alphabetically (A-Z). All entries in each char array are lowercase. I'm having a hard time finding info about how to do this online or in a C book that I have. Could anyone point me in the right direction?

James Manes
  • 526
  • 1
  • 11
  • 23
  • See the related links. Here is a similar [one](http://stackoverflow.com/questions/6105513/need-help-using-qsort-with-an-array-of-structs?rq=1). Basically you have to use qsort method – Shiplu Mokaddim Dec 06 '12 at 22:58

1 Answers1

4

As per the signature of qsort.

void qsort ( void * base, size_t num, size_t size,
             int ( * compar ) ( const void *, const void * ) );

Define the compare function.

int compare_record_type(const void* a, const void* b) {
    return strncmp(((*record_type)a)->name, ((*record_type)b)->name, MAX)
}

And invoke qsort like this.

qsort(record, 100, sizeof(record_type), compare_record_type)

More info at cplusplus.com

udoprog
  • 1,825
  • 14
  • 14