Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!elroy.jpl.nasa.gov!sdd.hp.com!think.com!linus!linus!mbunix.mitre.org!pathak From: pathak@mbunix.mitre.org (Pathak) Newsgroups: comp.lang.c Subject: Re: Generic array manipulation routine Keywords: C, arrays, pointers Message-ID: <1991Jan30.001053.10622@linus.mitre.org> Date: 30 Jan 91 00:10:53 GMT References: <2163@enuxha.eas.asu.edu> Sender: news@linus.mitre.org (News Service) Organization: The MITRE Corp., Bedford MA Lines: 44 Nntp-Posting-Host: mbunix.mitre.org 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