[comp.lang.c] Generic array manipulation routine

hurwitz@enuxha.eas.asu.edu (Roger A. Hurwitz) (01/29/91)

Hello, Cpersons;

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 *));

Where _base_ is a pointer to the 0th element in the array, _nelem_
is the number of elements in the array, and _width_ is the size
in bytes of each array element.  Given these parameters, I suppose
one could cast the void pointer to a char pointer and manipulate
the elements byte-by-byte, but I was wondering if there is a "better"
approach.

Thanks in advance for any help,

Roger Hurwitz
hurwitz@enuxha.eas.asu.edu

pathak@mbunix.mitre.org (Pathak) (01/30/91)

In article <2163@enuxha.eas.asu.edu> hurwitz@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@mitre.org
#include <std.disclaimer>