Programming Challenge

Daniel E. Platt platt at ndla.UUCP
Fri Dec 21 04:46:10 AEST 1990


In article <1990Dec15.015355.15683 at fmrco>, harold at fmrco (Harold Naparst) writes:
> 
> I am trying to write a function which will return the index
> of the smallest element of an array.  I want the routine
> to work for any type array.  That is, I don't want to write
> a separate routine for each type of array (real or double or
> integer).  How can I do this ?  I tried playing around with 
> the GNU C typeof operator, but couldn't figure it out.  Any ideas ?
> 

Hi,

I think that you'd need to provide some sort of comparator function that
will actually do the comparison between the various elements, and all you
need to be able to do is pass the size of the data objects so that you can
compute the comparison pointers.  Example:

int least_find(base, nel, size, compar)
char *base;
int nel, size;
int (*compar)();
{
	int i, i_least;

	for (i = i_least = 0; i < nel; i++)
		if ((*compar)(base + i * size, base + i_least * size) < 0)
			i_least = i;

	return i_least;
}

Then, all you'd need to do is pass the function in compar that would handle
the comparison between your two types, and which would yield a value > 0, = 0,
or < 0 depending on which element was larger.

/* a function that will compare two integers */
int comp(u, v)
int *u, *v;
{
	return (*v - *u);
}

/*
** a section of code that will find the smallest out of N elements of array
** ar[] of ints using comp().
*/

	least = least_find(ar, N, sizeof(int), comp);

Hope this gives you more of a feel of how this has been handled in the
past...

Dan



More information about the Comp.lang.c mailing list