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?

1
  • See the related links. Here is a similar one. Basically you have to use qsort method Commented Dec 6, 2012 at 22:58

1 Answer 1

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

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

Comments

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.