Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting A Structure By Date 1

Status
Not open for further replies.

Spannerman

Programmer
Dec 31, 2000
26
GB
How do you sort a structure by date? Does anyone have a chunk of ready-made code for C? My structure or file is:

Date
Code
Description
Size
Standard Stock
Current Stock
 
You can use the standard function qsort() and accomplish that with little effort.

#include <stdlib.h>

/* ... */

/* This is the comparison function that qsort() will use to sort the
* array members.
*/
int compareDate(const void *d1,const void *d2)
{
struct item *a=(struct item *)d1;
struct item *b=(struct item *)d2;

/* Just makes ascii comparison, which will work as is assuming your
* date item is in order of year, month, month day
*/
return strcmp(a->date,b->date);
}

/* ... */

struct item myStock[NUM_OF_ITEMS];

/* Populate array */

/* Sort it, you pass qsort the address of the 1st element of your array of structures
* (1st parameter) and it just needs to know how many items in the array (2nd parameter)
* and how big each item is (3rd parameter) and which function it should call to make
* comparisons between array items. It sorts the array in place.
*/
qsort(&amp;myStock,sizeof myStock / sizeof(struct item),sizeof(struct item),compareDate);

/* ... */

HTH,

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top