Programming in C

(Barry) #1
General Utility Functions 491

arguments.”qsortcalls this function whenever it needs to compare two elements in
the array, passing it pointers to the elements to compare.The function, which is user-
supplied, is expected to compare the two elements and return a value less than zero,
equal to zero, or greater than zero if the first element is less than, equal to, or greater
than the second element, respectively.
Here is an example of how to use qsortto sort an array of 1,000 integers called
data:
#include <stdlib.h>
...
int main (void)
{
int data[1000], comp_ints (void *, void *);
...
qsort (data, 1000, sizeof(int), comp_ints);
...
}

int comp_ints (void *p1, void *p2)
{
int i1 = * (int *) p1;
int i2 = * (int *) p2;
return i1 - i2;
}
Another routine called bsearch, which is not described here, takes similar arguments
to qsortand performs a binary search of an ordered array of data.
int rand (void)
Returns a random number in the range [0,RAND_MAX], where RAND_MAXis defined in
<stdlib.h>and has a minimum value of 32767. See also srand.
void srand (seed)
Seeds the random number generator to the unsigned intvalue seed.
int system (s)
Gives the command contained in the character array pointed to by sto the system
for execution, returning a system-defined value. If sis the null pointer,system
returns a nonzero value if a command processor is available to execute your com-
mands.
As an example, under Unix, the call
system ("mkdir /usr/tmp/data");
causes the system to create a directory called /usr/tmp/data(assuming you have the
proper permissions to do so).

21 0672326663 AppB 6/10/04 2:03 PM Page 491

Free download pdf