Chapter 15 - Power Programming: Tapping Important C and C++ Libraries
Visual C++ 6: The Complete Reference
Chris H. Pappas and William H. Murray, III
Copyright 1998 The McGraw-Hill Companies
Standard Library Functions (STDLIB.H)
The standard library macros and functions comprise a powerful group of items for data conversion, memory allocation, and other miscellaneous operations. The most frequently encountered macros and functions are shown in Table 15-2. The prototypes are found in STDLIB.H.
Table 15-2: Popular Standard Library Functions
Macro or Function
Description
_exit( )
Terminates a program
_lrotl( )
Rotates an unsigned long to the left
_lrotr( )
Rotates an unsigned long to the right
_rotl( )
Rotates an unsigned integer to the left
_rotr( )
Rotates an unsigned integer to the right
abort( )
Aborts program; terminates abnormally
abs( )
Absolute value of an integer
atexit( )
Registers termination function
atof( )
Converts a string to a float
atoi( )
Converts a string to an integer
atol( )
Converts a string to a long
bsearch( )
Binary search on an array
calloc( )
Allocates main memory
div( )
Divides integers
_ecvt( )
Converts a float to a string
exit( )
Terminates a program
_fcvt( )
Converts a float to a string
free( )
Frees memory
_gcvt( )
Converts a float to a string
getenv( )
Gets a string from the environment
_itoa( )
Converts an integer to a string
labs( )
Absolute value of a long
ldiv( )
Divides two longintegers
_ltoa( )
Converts a long to a string
malloc( )
Allocates memory
_putenv( )
Puts a string in the environment
qsort( )
Performs a quick sort
rand( )
Random number generator
realloc( )
Reallocates main memory
srand( )
Initializes random number generator
strtod( )
Converts a string to a double
strtol( )
Converts a string to a long
strtoul( )
Converts a string to an unsigned long
_swab( )
Swaps bytes from s1 to s2
system( )
Invokes DOS COMMAND.COM file
_ultoa( )
Converts an unsigned long to a string
As you examine Table 15-2, notice that almost half of the functions shown perform a data conversion from one format to another.
You’ll make use of many of these functions and macros as you develop your own C and C++ programs.
Performing Data Conversions
The first important group of functions described in STDLIB.H are the data converting functions. Their principal job is to convert data from one data type to another. For example, the atol( ) function converts string information to a long.
The syntax of each function is shown in the following list of function prototypes:
In these functions, *s points to a string, value is the number to be converted, n represents the number of digits in the string, and dec locates the decimal point relative to the start of the string. The variable sign represents the sign of the number, buf is a character buffer, radix represents the number base for the converted value, and endptr is usually null. If not a null value, the function sets it to the character that stops the scan.
The use of several of these functions is illustrated in the following programs.
Changing a float to a String
The fcvt( ) function converts a float to a string. It is also possible to obtain information regarding the sign and location of the decimal point.
/* * fcvt.c * Demonstrating the use of the fcvt( ) function. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
#include <stdio.h> #include <stdlib.h>
main( ) { int dec_pt,sign; char *ch_buffer; int num_char=7;
ch_buffer = fcvt(-234.5678,num_char,&dec_pt,&sign); printf(“The buffer holds: %s\n”,ch_buffer); printf(“The sign (+=0, -=1) is stored as a: %d\n”,sign); printf(“The decimal place is %d characters from right\n”, dec_pt); return (0); }
The output from this program is shown here:
The buffer holds: 2345678000 The sign (+=0, -=1) is stored as a: 1 The decimal place is 3 characters from right
Changing a String to a long integer
The strtol( ) function converts the specified string, in the given base, to its decimal equivalent. The following example shows a string of binary characters that will be converted to a decimal number:
/* * strtol.c * Demonstrating the use of the strtol( ) function. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
#include <stdlib.h> #include <stdio.h>
main( ) { char *s="101101",*endptr; long long_number;
long_number=strtol(s,&endptr,2); printf(“The binary value %s is equal to %ld decimal.\n”, s,long_number); return (0); }
In this example, “101101" is a string that represents several binary digits. The program produces the following results:
The binary value 101101 is equal to 45 decimal.
This is an interesting function since it allows a string of digits to be specified in one base and converted to another. This function would be a good place to start if you wanted to develop a general base change program.
Performing Searches and Sorts
The bsearch( ) function is used to perform a binary search of an array. The qsort( ) function performs a quick sort. The lfind( ) function can be used to perform a linear search for a key in an array of sequential records. The lsearch( ) function performs a linear search on a sorted or unsorted table. Examine the function syntax shown in the following listing:
Here, key represents the search key, base is the array to search, nelem contains the number of elements in the array, width is the number of bytes for each table entry, fcmp is the comparison routine used, and num reports the number of records.
The next application shows the use of two of the search and sort functions just described.
Using qsort( ) to Sort a Group of Integers
In C and C++, as in any language, sorting data is very important. Visual C++ provides the qsort( ) function for sorting data. The following example is one application in which qsort( )can be used.
/* * qsort.c * Demonstrating the use of the qsort( ) function. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
#include <stdio.h> #include <stdlib.h>
int int_comp(const void *i,const void *j);
int list[12]={95,53,71,86,11,28,34,53,10,11,74,-44};
main( ) { int i;
qsort(list,12,sizeof(int),int_comp);
printf(“The array after qsort:\n”); for(i=0;i<12;i++) printf(“%d ”,list[i]); return (0); }
The original numbers, in the variable list, are signed integers. The qsort( ) function will arrange the original numbers in ascending order, leaving them in the variable list. Here, the original numbers are sorted in ascending order:
The array after qsort: —44 10 11 11 28 34 53 53 71 74 86 95
Can qsort( ) be used with floats? Why not alter the previous program and see?
Finding an Integer in an Array of integers
You use the bsearch( ) function to perform a search in an integer array. The search value for this example is contained in search_number.
/* * bsearch.c * Demonstrating the use of the bsearch( ) function. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
#include <stdlib.h> #include <stdio.h>
int int_comp(const void *i,const void *j);
int data_array[]={100,200,300,400,500, 600,700,800,900};
main( ) { int *search_result; int search_number=400;
printf(“Is 400 in the data_array? ”); search_result=bsearch(&search_number,data_array,9, sizeof(int),int_comp); if (search_result) printf(“Yes!\n”); else printf(“No!\n”); return (0); }
This application sends a simple message to the screen regarding the outcome of the search, as shown next.
Is 400 in the data_array? Yes!
You can also use this function to search for a string of characters in an array.
Miscellaneous Operations
There are several miscellaneous functions, listed in Table 15-3 and described in this section, that perform a variety of diverse operations. These operations include calculating the absolute value of an integer and bit rotations on an integer.
Table 15-3: Miscellaneous Functions
Function
Description
Abort or End:
void abort(void)
Returns an exit code of 3
int atexit(atexit_t func)
Calls function prior to exit
void exit(int status)
Returns zero for normal exit
int system(const char * command)
Command is a DOS command
void_exit(int status)
Terminates with no action
Math:
div_t div(int number,int denom)
Divides and returns quotient and remainder in div_t
int abs(int x)
Determines absolute value of x
long labs(long x)
Determines absolute value of x
ldiv_t ldiv(long numerator,long denominator)
Similar to div( ) with longs
int rand(void)
Calls random number generator
void srand(unsigned seed)
Seeds random number generator
Rotate:
unsigned long_lrotl(unsigned long val,int count)
Rotates the longval to the left
unsigned long_l lrotr(unsigned long val,int count)
Rotates the longval to the right
unsigned _rotl(unsigned val,int count)
Rotates the integerval to the left
unsigned _rotr(unsigned val,int count)
Rotates the integerval to the right
Miscellaneous:
char * getenv(const char * name)
Gets environment string
int putenv(const char * name)
Puts environment string
void _swap(char * from, char * to,int nbytes)
Swaps the number of characters in nbytes
Bit rotation functions give you the ability to perform operations that were once just in the realm of assembly language programmers.
Using the Random Number Generator
Visual C++ provides a random number function. The random number generator can be initialized or seeded with a call to srand( ). The seed function accepts an integer argument and starts the random number generator.
/* * rand.c * Demonstrating the use of the srand( ) and rand( ), * random number functions. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
#include <stdlib.h> #include <stdio.h>
main( ) { int x;
srand(3);
for (x=0;x<8;x++) printf(“Trial #%d, random number=%d\n”, x,rand( )); return (0); }
An example of random numbers generated by rand( ) is shown here:
Trial #0, random number=48 Trial #1, random number=7196 Trial #2, random number=9294 Trial #3, random number=9091 Trial #4, random number=7031 Trial #5, random number=23577 Trial #6, random number=17702 Trial #7, random number=23503
Random number generators are important in programming for statistical work and for applications that rely on the generation of random patterns. It is important that the numbers produced be unbiased—that is, that all numbers have an equal probability of appearing.
Rotating Data Bits
C and C++ provide a means of rotating the individual bits of integers and longs to the right and to the left. In the next example, two rotations in each direction are performed:
/* * rotate.c * Demonstrating the use of the _rotl( ) and _rotr( ) * bit rotate functions. * Copyright (c) Chris H. Pappas and William H. Murray, 1998 */
#include <stdio.h> #include <stdlib.h>
main( ) { unsigned int val = 0x2345;
printf(“rotate bits of %X to the left 2 bits and get %X\n”, val,_rotl(val,2)); printf(“rotate bits of %X to the right 2 bits and get %X\n”, val,_rotr(val,2)); return(0); }
Here are the results:
rotate bits of 2345 to the left 2 bits and get 8D14 rotate bits of 2345 to the right 2 bits and get 400008D1
Note that the original numbers are in hexadecimal format.
The use of the bit rotation functions and the use of logical operators such as and, or, xor, and so on, give C and C++ the ability to manipulate data bit by bit.