[ back to toc ]

Qsort() malloc() compare()

Date: 2002/03/25 10:17

Q:
Hello Peter,
First,thanks for your previous answer.You told me to allocate an array of
pointers to memory and compare the pointers.Unfortunately,dolt that I am,
I keep getting errors! Could you please give me the 5-6+ lines of
necessary example code(declaration/qsort/malloc/compare) which I need? The
former question is shown below.
I am to read a text-file and sort the records by ascending customer number
code,using qsort and malloc and compare().This text-file contains 3
different types of records,separated from each other by \n.I don't know
the size of the text-file,and have to read the file and work out the no.
of records.Each of the 3 records has a record-type as a first
character(i,d,c) and the next 5 characters of each record is the customer
number code.Otherwise the records are of differing length and variables.
I used strncmp but no go;I have tried every combination I could think
of,but no luck.

I would be most appreciative of any assistance.
*NAME-DELETED* *NAME-DELETED*
A:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct line {
int len;
char *l;
} Line, *pLine;

static int mycompare(pLine *a, pLine *b){
return strcmp((*a)->l,(*b)->l);
}

main(){
FILE *fp;
char buffer[200];
pLine tosort[100];
int i;
int j;

fp = fopen("testq.c","r");

i = 0;
while( ! feof(fp) ){
fgets(buffer,200,fp);
tosort[i] = malloc(sizeof(struct line));
tosort[i]->l = strdup(buffer);
tosort[i]->len = strlen(buffer);
i++;
}
fclose(fp);

// print out the lines unsorted
for( j=0 ; j<i ; j++ ){
printf("%s",tosort[j]->l);
}

qsort(tosort, // what to sort
i, // number of elements to sort
sizeof(pLine), // size of an element
(void *)mycompare); // compare function

// print out the lines sorted
for( j=0 ; j<i ; j++ ){
printf("%s",tosort[j]->l);
}
}

[ back to toc ]