-
Using malloc() & qsort with a union
Help! I'm stuck & getting very frustrated, I have 2 questions.
A file contains records of 3 varying lengths, hence 3 structures and a union is used.
union a_rec{
struct a old;
struct b delete;
struct c new;
};
I have used malloc() to allocate some memory:
pointer to start
of memory = (union a_rec*)malloc(no_of_recs x Size);
Q1. How do you now put the records from the file into this area of allocated memory?
All the records (structures) have a code number which should be used to sort them - qsort is used to do this.
qsort (ptr, no_of_recs, Size, compare);
This is where I have a problem - the 'compare' function.
int compare(const void *a, const void *b)
{
return(strcmp(((union a_rec*)a)->old.number, ((union a_rec*)
b)->old.number))
}
Q2. The above asumes the record is (structure) 'old', but how do you compare the numbers no matter which type of record (structure) it is? There are 3 types in the file and this, to me, will only compare 'old' record numbers, what about 'delete' and 'new'?
-