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 (AZ). 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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.