Generic array manipulation routine

Pathak pathak at mbunix.mitre.org
Wed Jan 30 11:10:53 AEST 1991


In article <2163 at enuxha.eas.asu.edu> hurwitz at enuxha.eas.asu.edu (Roger A. Hurwitz) writes:
>
>I was hoping for some help on how to write a single C function
>for manipulating arrays, that can be called without change for
>arrays with elements of differing types.  For example, the
>qsort() function I use in Borland's Turbo C seems to do this.
>Borland's qsort() has the following syntax;
>
>	void qsort (void *base, size_t nelem, size_t width, 
>		int (*fcmp) (const void *, const void *));
		^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The part of the prototype I highlighted is a pointer to a function that
takes two elements.  Borland's qsort requires you to give it a function that
handles the comparision of two elements and returns:

int < 0 if is element1 < element2
int = 0 if is element1 = element2
int > 0 if is element1 > element2

Qsort has no idea of the data type of the element .  However, your 
function does and it is your function "processes" the data types.

You could do something similar by using the same method
For example, you could implement a generic sorted list by:

void insert_element (llist *head, void *element, 
	int (*comp_func) (const void *, const void *));

The comparision function would perform the exact same comparision as the
function you pass to quick sort. The insert function would look like this:

void insert_element(/*arg list goes here */){
while((head->next != NULL) && ( (*comp_funct)(head->element, element) < 0))
	head=head->next;
/* We have location to insert element so insert it*/
/* YOUR CODE GOES HERE */
}

I hope this helps you out.

Heeren Pathak
pathak at mitre.org
#include <std.disclaimer>



More information about the Comp.lang.c mailing list