20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

General Utility Functions<br />

491<br />

arguments.” qsort calls this function whenever it needs to compare two elements <strong>in</strong><br />

the array, pass<strong>in</strong>g it po<strong>in</strong>ters to the elements to compare.The function, which is usersupplied,<br />

is expected to compare the two elements and return a value less than zero,<br />

equal to zero, or greater than zero if the first element is less than, equal to, or greater<br />

than the second element, respectively.<br />

Here is an example of how to use qsort to sort an array of 1,000 <strong>in</strong>tegers called<br />

data:<br />

#<strong>in</strong>clude <br />

...<br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

<strong>in</strong>t data[1000], comp_<strong>in</strong>ts (void *, void *);<br />

...<br />

qsort (data, 1000, sizeof(<strong>in</strong>t), comp_<strong>in</strong>ts);<br />

...<br />

}<br />

<strong>in</strong>t comp_<strong>in</strong>ts (void *p1, void *p2)<br />

{<br />

<strong>in</strong>t i1 = * (<strong>in</strong>t *) p1;<br />

<strong>in</strong>t i2 = * (<strong>in</strong>t *) p2;<br />

return i1 - i2;<br />

}<br />

Another rout<strong>in</strong>e called bsearch, which is not described here, takes similar arguments<br />

to qsort and performs a b<strong>in</strong>ary search of an ordered array of data.<br />

<strong>in</strong>t rand (void)<br />

Returns a random number <strong>in</strong> the range [0, RAND_MAX], where RAND_MAX is def<strong>in</strong>ed <strong>in</strong><br />

and has a m<strong>in</strong>imum value of 32767. See also srand.<br />

void srand (seed)<br />

Seeds the random number generator to the unsigned <strong>in</strong>t value seed.<br />

<strong>in</strong>t system (s)<br />

Gives the command conta<strong>in</strong>ed <strong>in</strong> the character array po<strong>in</strong>ted to by s to the system<br />

for execution, return<strong>in</strong>g a system-def<strong>in</strong>ed value. If s is the null po<strong>in</strong>ter, system<br />

returns a nonzero value if a command processor is available to execute your commands.<br />

As an example, under Unix, the call<br />

system ("mkdir /usr/tmp/data");<br />

causes the system to create a directory called /usr/tmp/data (assum<strong>in</strong>g you have the<br />

proper permissions to do so).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!