This is what I described:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DEFAULT_NUM_RECORDS 100
#define SAMPLE_SIZE 20
#define SAMPLE_NUM_FIELDS 10
#define NAME_LENGTH 30
#define NUM_FIELDS 52
typedef struct
{
char name[NAME_LENGTH];
int data[NUM_FIELDS];
}
person;
void make_random_people (person * p, int n);
int compare_persons (const void * p,
const void * q);
int main (int argc, char * argv[])
{
int i, j, num;
person * people;
person ** ptrs;
srand ((unsigned)time(NULL));
if (argc<2 || sscanf(argv[1],"%d",&num)!=1 || num<1)
num = DEFAULT_NUM_RECORDS;
puts ("Allocating memory...");
people = (person*) malloc (num*sizeof(person));
ptrs = (person**) malloc (num*sizeof(person*));
if (!people || !ptrs)
{
fprintf (stderr, "Not enough memory.\n");
free (people);
free (ptrs);
return -1;
}
puts ("Making up some random data...");
make_random_people (people, num);
puts ("Preparing array of pointers...");
for (i=0; i<num; i++)
ptrs[i] = people + i;
printf ("Sorting %d elements...\n", num);
qsort (ptrs, num, sizeof(person*), compare_persons);
printf ("Data of first %d persons:\n", SAMPLE_SIZE);
for (i=0; i<SAMPLE_SIZE; i++)
{
printf ("%-10s ", ptrs[i]->name);
for (j=0; j<SAMPLE_NUM_FIELDS; j++)
printf ("%4d", ptrs[i]->data[j]);
putchar ('\n');
}
puts ("Freeing memory...");
free (people);
free (ptrs);
return 0;
}
int compare_persons (const void * p, const void * q)
{
person * a = *(person**)p;
person * b = *(person**)q;
int i;
for (i=0; i<NUM_FIELDS; i++)
{
if (a->data[i] > b->data[i]) return 1;
if (a->data[i] < b->data[i]) return -1;
}
return 0;
}
void make_random_people (person * p, int n)
{
int i, j;
for (i=0; i<n; i++)
{
sprintf (p[i].name, "Jim_%d", i);
for (j=0; j<NUM_FIELDS; j++)
p[i].data[j] = (int)(rand()*(999.0/RAND_MAX));
}
}