home *** CD-ROM | disk | FTP | other *** search
- /* ------------------------------------------------------ */
- /* QS.C */
- /* Sorting arrays of structures */
- /* (c) 1990 Borland International */
- /* All rights reserved. */
- /* ------------------------------------------------------ */
- /* veröffentlicht in: DOS toolbox 1'91/92 */
- /* ------------------------------------------------------ */
-
- /*
- The following code demonstrates how to use qsort() to sort
- an array of structures. After entering this small program,
- step through it with the IDE debugger, placing a watch on
- the variables in sort_function() to better understand what
- is happening.
- */
-
- #include <stdio.h> // for printf()
- #include <stdlib.h> // for qsort()
- #include <string.h> // for strcmp()
- #include <dos.h> // for MK_FP()
-
- int sort_function(const void *a, const void *b);
-
- struct foo {
- char *c;
- int xx;
- };
-
- struct foo *list[4];
- struct foo a1 = {"cat",3 };
- struct foo a2 = {"cab",3};
- struct foo a3 = {"cap",2 };
- struct foo a4 = {"cal",1 };
-
- // ------------------------------------------------------- *
- int main(void)
- {
- int x;
- list[0] = &a1;
- list[1] = &a2;
- list[2] = &a3;
- list[3] = &a4;
-
- qsort((void *) list, 4, sizeof(list[0]), sort_function);
- for (x = 0; x < 4; x++)
- printf("%s\n", list[x]->c);
- return 0;
- } // end of main()
-
- /* ------------------------------------------------------ */
- /* sort_function - */
- /* ------------------------------------------------------ */
-
- int sort_function(const void *a, const void *b) {
- unsigned int aa, bb; // Will be used for offset address
- struct foo *ap,*bp;
-
- aa = *(unsigned*) a; // a and b point to an address
- // which in turn
- bb = *(unsigned*) b; // points to the offset address of
- // the struct
-
- // Make a far pointer to struct address
-
- ap = (struct foo*) MK_FP(_DS, aa);
- bp = (struct foo*) MK_FP(_DS, bb);
-
- return(strcmp(ap->c,bp->c));
- } // end of sort_function()
- /* ------------------------------------------------------ */
- /* Ende von QS.C */
-
-