--- In [email protected], "Rick Bowers" <[EMAIL PROTECTED]> wrote:
>
> I am trying to sort an array of pointers to a structure.
Hi Rick- below is an example program which sorts an array of
structures and an array of pointers to structures. Not sure whether
you wanted C or C++ - I only do C I'm afraid. Hope it helps.
John
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_ENTRIES 10
typedef struct
{
char c;
} ENTRY;
/* Array of structures. */
static ENTRY linedata[MAX_ENTRIES] =
{
{'q'}, {'w'}, {'e'}, {'r'}, {'t'}, {'y'}, {'u'}, {'i'}, {'o'}, {'p'}
};
/* Array of pointers to structures. */
static ENTRY *filters[MAX_ENTRIES];
/* For comparing 2 ENTRY structures. */
static int cmpEntries(const ENTRY *e1, const ENTRY *e2)
{
printf("comparing %c %c\n", e1->c, e2->c);
if (e1->c < e2->c) return -1;
if (e1->c > e2->c) return 1;
return 0;
}
/* For use with qsort() and array of structures. */
static int compareEntry(const void *a, const void *b)
{
return cmpEntries(a, b);
}
/* For use with qsort() and array of pointers to structures. */
static int compareEntryPtr(const void *a, const void *b)
{
ENTRY *const *pE1 = a;
ENTRY *const *pE2 = b;
return compareEntry(*pE1, *pE2);
}
/* Print an array of structures. */
static void printEntries(const char *s, const ENTRY *p)
{
int i;
printf("%s:", s);
for (i = MAX_ENTRIES; i--; p++)
{
printf(" %c", p->c);
}
printf("\n");
}
/* Print an array of pointers to structures. */
static void printEntriesPtr(const char *s, ENTRY *const *pp)
{
int i;
printf("%s:", s);
for (i = MAX_ENTRIES; i--; pp++)
{
printf(" %c", (*pp)->c);
}
printf("\n");
}
int main(void)
{
int i;
/* Initialise the array of pointers to structures. */
for (i = MAX_ENTRIES; i--; )
{
filters[i] = malloc(sizeof *filters[i]);
filters[i]->c = toupper(linedata[i].c);
}
printEntries("linedata before", linedata);
qsort(linedata, MAX_ENTRIES, sizeof *linedata, compareEntry);
printEntries("linedata after", linedata);
printEntriesPtr("filters before", filters);
qsort(filters, MAX_ENTRIES, sizeof *filters, compareEntryPtr);
printEntriesPtr("filters after", filters);
return 0;
}