BUY THIS BOOK
Add to Cart

Print Book $9.95


Add to Cart

Print+PDF $12.93

Add to Cart

PDF $7.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £6.95

What is this?

Looking to Reprint or License this content?


C Pocket Reference
C Pocket Reference By Peter Prinz, Ulla Kirch-Prinz
Translated by  Tony Crawford
November 2002
Pages: 142

Cover | Table of Contents


Table of Contents

Chapter 1: C Pocket Reference
The programming language C was developed in the 1970s by Dennis Ritchie at Bell Labs (Murray Hill, New Jersey) in the process of implementing the Unix operating system on a DEC PDP-11 computer. C has its origins in the typeless programming language BCPL (Basic Combined Programming Language, developed by M. Richards) and in B (developed by K. Thompson). In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard.
C is a highly portable language oriented towards the architecture of today's computers. The actual language itself is relatively small and contains few hardware-specific elements. It includes no input/output statements or memory management techniques, for example. Functions to address these tasks are available in the extensive C standard library.
C's design has significant advantages:
  • Source code is highly portable
  • Machine code is efficient
  • C compilers are available for all current systems
The first part of this pocket reference describes the C language, and the second part is devoted to the C standard library. The description of C is based on the ANSI X3.159 standard. This standard corresponds to the international standard ISO/IEC 9899, which was adopted by the International Organization for Standardization in 1990, then amended in 1995 and 1999. The ISO/IEC 9899 standard can be ordered from the ANSI web site; see http://ansi.org/public/std_info.html.
The 1995 standard is supported by all common C compilers today. The new extensions defined in the 1999 release (called "ANSI C99" for short) are not yet implemented in many C compilers, and are therefore specially labeled in this book. New types, functions, and macros introduced in ANSI C99 are indicated by an asterisk in parentheses (*).
The following typographic conventions are used in this book:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
The programming language C was developed in the 1970s by Dennis Ritchie at Bell Labs (Murray Hill, New Jersey) in the process of implementing the Unix operating system on a DEC PDP-11 computer. C has its origins in the typeless programming language BCPL (Basic Combined Programming Language, developed by M. Richards) and in B (developed by K. Thompson). In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard.
C is a highly portable language oriented towards the architecture of today's computers. The actual language itself is relatively small and contains few hardware-specific elements. It includes no input/output statements or memory management techniques, for example. Functions to address these tasks are available in the extensive C standard library.
C's design has significant advantages:
  • Source code is highly portable
  • Machine code is efficient
  • C compilers are available for all current systems
The first part of this pocket reference describes the C language, and the second part is devoted to the C standard library. The description of C is based on the ANSI X3.159 standard. This standard corresponds to the international standard ISO/IEC 9899, which was adopted by the International Organization for Standardization in 1990, then amended in 1995 and 1999. The ISO/IEC 9899 standard can be ordered from the ANSI web site; see http://ansi.org/public/std_info.html.
The 1995 standard is supported by all common C compilers today. The new extensions defined in the 1999 release (called "ANSI C99" for short) are not yet implemented in many C compilers, and are therefore specially labeled in this book. New types, functions, and macros introduced in ANSI C99 are indicated by an asterisk in parentheses (*).
The following typographic conventions are used in this book:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Fundamentals
A C program consists of individual building blocks called functions , which can invoke one another. Each function performs a certain task. Ready-made functions are available in the standard library; other functions are written by the programmer as necessary. A special function name is main( ): this designates the first function invoked when a program starts. All other functions are subroutines.
Figure 1-1 illustrates the structure of a C program. The program shown consists of the functions main() and showPage() , and prints the beginning of a text file to be specified on the command line when the program is started.
Figure 1-1: A C program
The statements that make up the functions, together with the necessary declarations and preprocessing directives, form the source code of a C program. For small programs, the source code is written in a single source file . Larger C programs consist of several source files, which can be edited and compiled separately. Each such source file contains functions that belong to a logical unit, such as functions for output to a terminal, for example. Information that is needed in several source files, such as declarations, is placed in header files. These can then be included in each source file via the #include directive.
Source files have names ending in .c; header files have names ending in .h. A source file together with the header files included in it is called a translation unit .
There is no prescribed order in which functions must be defined. The function showPage() in Figure 1-1 could also be placed before the function main(). A function cannot be defined within another function, however.
The compiler processes each source file in sequence and decomposes its contents into
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic Types
The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. Similarly, the type of a function determines how its return value is to be interpreted.
Types can be either predefined or derived. The predefined types in C are the basic types and the type void. The basic types consist of the integer types and the floating types.
There are five signed integer types: signed char , short int (or short), int , long int (or long), and long long int (*) (or long long (*)). For each of these types there is a corresponding unsigned integer type with the same storage size. The unsigned type is designated by the prefix unsigned in the type specifier, as in unsigned int.
The types char , signed char, and unsigned char are formally different. Depending on the compiler settings, however, char is equivalent either to signed char or to unsigned char. The prefix signed has no meaning for the types short, int, long, and long long (*), however, since they are always considered to be signed. Thus short and signed short specify the same type.
The storage size of the integer types is not defined; however, their width is ranked in the following order: char <= short <= int <= long <= long long (*). Furthermore, the size of type short is at least 2 bytes, long at least 4 bytes, and long long at least 8 bytes. Their value ranges for a given implementation are found in the header file limits.h .
ANSI C99 also introduces the type _Bool to represent Boolean values. The Boolean value true is represented by 1 and false by 0. If the header file stdbool.h has been included, then bool can be used as a synonym for _Bool and the macros true and false for the integer constants
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constants
Every constant is either an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants, which are described in Section 1.10.1. Every constant has a type that is determined by its value and its notation.
Integer constants can be represented as ordinary decimal numbers, octal numbers, or hexadecimal numbers:
  • A decimal constant (base 10) begins with a digit that is not 0; for example: 1024
  • An octal constant (base 8) begins with a 0; for example: 012
  • A hexadecimal constant (base 16) begins with the two characters 0x or 0X; for example: 0x7f, 0X7f, 0x7F, 0X7F. The hexadecimal digits A to F are not case-sensitive.
The type of an integer constant, if not explicitly specified, is the first type in the appropriate hierarchy that can represent its value.
For decimal constants, the hierarchy of types is:
int, long, unsigned long, long long(*).
For octal or hexadecimal constants, the hierarchy of types is:
int, unsigned int, long, unsigned long, long long(*), 
unsigned long long(*).
Thus, integer constants normally have type int. The type can also be explicitly specified by one of the suffixes L or l (for long), LL (*) or ll (*) (for long long (*)), and/or U or u (for unsigned). Table 1-6 provides some examples.
Table 1-6: Examples of integer constants
Decimal
Octal
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expressions and Operators
An expression is a combination of operators and operands. In the simplest case, an expression consists simply of a constant, a variable, or a function call. Expressions can also serve as operands, and can be joined together by operators into more complex expressions.
Every expression has a type and, if the type is not void, a value. Some examples of expressions follow:
4 * 512                         // Type: int  
printf("An example!\n")         // Type: int 
1.0 + sin(x)                    // Type: double
srand((unsigned)time(NULL))     // Type: void
(int*)malloc(count*sizeof(int)) // Type: int *
In expressions with more than one operator, the precedence of the operators determines the grouping of operands with operators. The arithmetic operators *, /, and %, for example, take precedence over + and -. In other words, the usual rules apply for the order of operations in arithmetic expressions. For example:
4 + 6 * 512    // equivalent to 4 + (6 * 512)
If a different grouping is desired, parentheses must be used:
(4 + 6) * 512
Table 1-8 lists the precedence of operators.
Table 1-8: Precedence of operators
Priority
Operator
Grouping
1
() [] -> .
left to right
2
! ~ ++ -- + - (type) * & sizeof
right to left
3
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Type Conversions
A type conversion yields the value of an expression in a new type. Conversion can be performed only on scalar types, i. e., arithmetic types and pointers.
A type conversion always conserves the original value, if the new type is capable of representing it. Floating-point numbers may be rounded on conversion from double to float, for example.
Type conversions can be implicit —i. e., performed by the compiler automatically—or explicit , through the use of the cast operator. It is considered good programming style to use the cast operator whenever type conversions are necessary. This makes the type conversion explicit, and avoids compiler warnings.
Operands of the types _Bool, char, unsigned char, short, and unsigned short, as well as bit-fields, can be used in expressions wherever operands of type int or unsigned int are permissible. In such cases, integer promotion is performed on the operands: they are automatically converted to int or unsigned int. Such operands are converted to unsigned int only if the type int cannot represent all values of the original type.
Thus C always "expects" values that have at least type int. If c is a variable of type char, then its value in the expression:
 c + '0'
is promoted to int before the addition takes place.
The operands of a binary operator may have different arithmetic types. In this case, the usual arithmetic conversions are implicitly performed to cast their values in a common type. However, the usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||.
If operands still have different types after integer promotion, they are converted to the type that appears highest in the hierarchy shown in Figure 1-4. The result of the operation also has this type.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Statements
A statement specifies an action to be performed, such as an arithmetic operation or a function call. Many statements serve to control the flow of a program by defining loops and branches. Statements are processed one after another in sequence, except where such control statements result in jumps.
Every statement that is not a block is terminated by a semicolon.
A block , also called a compound statement, groups a number of statements together into one statement. A block can also contain declarations.
The syntax for a block is:
{[list of declarations][list of statements]}
Here is an example of a block:
{ int i = 0;      /* Declarations  */
  static long a;
  extern long max;

  ++a;            /* Statements    */
  if( a >= max)
  {   . . .    }  /* A nested block */
  . . .
}
The declarations in a block normally precede the statements. However, ANSI C99 permits free placement of declarations.
New blocks can occur anywhere within a function block. Usually a block is formed wherever the syntax calls for a statement, but the program requires several statements. This is the case, for example, when more than one statement is to be repeated in a loop.
An expression statement is an expression followed by a semicolon. The syntax is:
[expression] ;
Here is an example of an expression statement:
 y = x;        // Assignment
The expression—an assignment or function call, for example—is evaluated for its side effects. The type and value of the expression are discarded.
A statement consisting only of a semicolon is called an empty statement , and does not peform any operation. For example:
for ( i = 0;  str[i] != '\0'; ++i )
   ;                     // Empty statement
The following statements can be used to control the program flow:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Declarations
A declaration determines the interpretation and properties of one or more identifiers. A declaration that allocates storage space for an object or a function is a definition. In C, an object is a data storage region that contains constant or variable values. The term "object" is thus somewhat more general than the term "variable."
In the source file, declarations can appear at the beginning of a block, such as a function block, or outside of all functions. Declarations that do not allocate storage space, such as function prototypes or type definitions, are normally placed in a header file.
ANSI C99 allows declarations and statements to appear in any order within a block.
The general syntax of a declaration is as follows:
[storage class] type  D1 [, D2, ...];
storage class
One of the storage class specifiers extern, static, auto, or register.
type
A basic type, or one of the following type specifiers: void, enum type (enumeration), struct or union type, or typedef name.
type may also contain type qualifiers, such as const.
D1 [, D2,...]
A list of declarators. A declarator contains at least one identifier, such as a variable name.
Some examples are:
char  letter;
int   i, j, k;
static  double rate, price;
extern char  flag;
Variables can be initialized—that is, assigned an initial value—in the declaration. Variable and function declarations are described in detail in the sections that follow.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
Every variable must be declared before it can be used. The declaration determines the variable's type, its storage class, and possibly its initial value. The type of a variable determines how much space it occupies in storage and how the bit pattern it stores is interpreted. For example:
float dollars = 2.5F;     // a variable of type float
The variable dollars designates a region in memory with a size of 4 bytes. The contents of these four bytes are interpreted as a floating-point number, and initialized with the value 2.5.
The storage class of a variable determines its scope, its storage duration, and its linkage. The scope can be either block or file (see Section 1.2.4, earlier in this book). Variables also have one of two storage durations:
Static storage duration
The variable is generated and initialized once, before the program begins. It exists continuously throughout the execution of the program.
Automatic storage duration
The variable is generated anew each time the program flow enters the block in which it is defined. When the block is terminated, the memory occupied by the variable is freed.
The storage class of a variable is determined by the position of its declaration in the source file and by the storage class specifier, if any. A declaration may contain no more than one storage class specifier. Table 1-18 lists the valid storage class specifiers.
Table 1-18: The storage class specifiers
Specifier
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Derived Types
A programmer can also define new types, including enumerated types and derived types. Derived types include pointers, arrays, structures, and unions.
The basic types and the enumerated types are collectively called the arithmetic types . The arithmetic types and the pointer types in turn make up the scalar types . The array and structure types are known collectively as the aggregate types .
Enumeration types are used to define variables that can only be assigned certain discrete integer values throughout the program. The possible values and names for them are defined in an enumeration. The type specifier begins with the keyword enum ; for example:
enum toggle { OFF, ON, NO = 0, YES };
The list of enumerators inside the braces defines the new enumeration type. The identifier toggle is the tag of this enumeration. This enumeration defines the identifiers in the list (OFF, ON, NO, and YES) as constants with type int.
The value of each identifier in the list may be determined explicitly, as in NO = 0 in the example above. Identifiers for which no explicit value is specified are assigned a value automatically based on their position in the list, as follows: An enumerator without an explicit value has the value 0 if it is the first in the list; otherwise its value is 1 greater than that of the preceding enumerator. Thus in the example above, the constants OFF and NO have the value 0, while ON and YES have the value 1.
Once an enumeration type has been defined, variables with the type can be declared within its scope. For example:
enum toggle t1, t2 = ON;
This declaration defines t1 and t2 as variables with type enum toggle, and also initializes t2 with the value ON, or 1.
Following is an enumeration without a tag:
enum { black, blue, green, cyan, red, magenta, white };
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions
Every C program contains at least the function main() , which is the first function executed when the program starts. All other functions are subroutines.
The definition of a function lists the statements it executes. Before a function can be called in a given translation unit, it must be declared. A function definition also serves as a declaration of the function. The declaration of a function informs the compiler of its return type. For example:
extern double pow();
Here pow() is declared as a function that returns a value with type double. Because function names are external names by default, the storage class specifier extern can also be omitted.
In ANSI C99, implicit function declarations are no longer permitted. Formerly, calls to undeclared functions were allowed, and the compiler implicitly assumed in such cases that the function returned a value of type int.
The declaration of the function pow() in the example above contains no information about the number and type of the function's parameters. Hence the compiler has no way of testing whether the arguments supplied in a given function call are compatible with the function's parameters. This missing information is supplied by a function prototype.
A function prototype is a declaration that indicates the types of the function's parameters as well as its return value. For example:
double pow( double, double );    // prototype of pow()
This prototype informs the compiler that the function pow() expects two arguments of type double, and returns a result of type double. Each parameter type may be followed by a parameter name. This name has no more significance than a comment, however, since its scope is limited to the function prototype itself. For example:
double pow( double base, double exponent );
Functions that do not return any result are declared with the type specifier void. For example:
void func1( char *str ); // func1 expects one string
                         // argument and has no return 
                         // value.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Linkage of Identifiers
An identifier that is declared more than once, whether in different scopes (in different files, for example) or in the same scope, may refer to the same variable or function. Identifiers must be "linked" in this way in order for a variable to be used "globally," across different source files, for example.
Each identifier has either external, internal, or no linkage. These three kinds of linkage have the following significance:
External linkage
An identifier with external linkage represents the same object or function throughout the entire program, i. e., in all source files and libraries belonging to the program. The identifier is made known to the linker.
When a second declaration of the same identifier with external linkage occurs, the linker associates the identifier with the same object or function. A declaration of an existing external object is sometimes called a reference declaration .
Internal linkage
An identifier with internal linkage represents the same object or function within a given translation unit. The linker has no information about identifiers with internal linkage. Thus they remain "internal" to the translation unit.
No linkage
If an identifier has no linkage, then any further declaration using the identifier declares something new, such as a new variable or a new type.
The linkage of an identifier is determined by its storage class; that is, by the position of the declaration and any storage class specifier included in it. Only identifiers of variables and functions can have internal or external linkage. All other identifiers, and identifiers of variables with automatic storage class, have no linkage. Table 1-20 summarizes this information.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Preprocessing Directives
The C compiler preprocesses every source file before performing the actual translation. The preprocessor removes comments and replaces macros with their definitions.
Every preprocessing directive appears on a line by itself, beginning with the character #. If the directive is long, it can be continued on the next line by inserting a backslash (\) as the last character before the line break.
#define
The #define directive is used to define macros.
Syntax:
define name[(parameter_list)]  [replacement_text]
               
The preprocessor replaces each occurrence of name or name(parameter_list) in the subsequent source code with replacement_text.
Examples:
#define  BUF_SIZE  512        // Symbolic constant
#define  MAX(a,b)  ((a) > (b) ? (a) : (b))
These directives define the macros BUF_SIZE and MAX. If the replacement text is a constant expression, the macro is also called a symbolic constant . Macros can also be nested; a macro, once defined, can be used in another macro definition.
In the previous example, the parentheses are necessary in order for the substitution to be performed correctly when MAX is used in an expression, or when complex expressions replace the parameters a and b. For example, the preprocessor replaces the macro invocation:
result = 2 * MAX( x, y & 0xFF );
with:
result = 2 * ( (x) > (y & 0xFF) ? (x) : (y & 0xFF) );
The # Operator
In the macro replacement text, the parameters of the macro may be preceded by the operator # (called the hash or stringizing operator). In this case, the preprocessor sets the corresponding argument in quotation marks, thus converting it into a string.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Standard Library
The remaining sections in this book describe the contents of the ANSI C library. The standard functions, types, and macros are grouped according to their purpose and areas of application. This arrangement makes it easy to find less well-known functions and macros. Each section also supplies the background information needed in order to make efficient use of the library's capabilities. New data types, functions, and macros introduced in ANSI C99 are indicated by an asterisk in parentheses (*).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Standard Header Files
All function prototypes, macros, and types in the ANSI library are contained in one or more of the following standard header files:
assert.h 
inttypes.h(*)
signal.h
stdlib.h
complex.h(*)
iso646.h(*)
stdarg.h
string.h
ctype.h
limits.h
stdbool.h(*)
tgmath.h(*)
errno.h
locale.h
stddef.h
time.h
fenv.h(*)
math.h
stdint.h(*)
wchar.h(*)
float.h
setjmp.h
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Input and Output
The ANSI library provides a suite of high-level functions to manage all kinds of input and output, with the appropriate buffering, as uniform data streams.
When a file is opened, for example, a new stream is created along with a file pointer , which is a pointer to a structure of type FILE that contains information about the stream. This information includes the address of the buffer, the number of bytes not yet read, and other information about the file itself. The file pointer is used to identify the file in all subsequent operations.
Devices such as the display are addressed in the same way as files. When the program starts, three streams are open by default, with the following file pointers:
stdin
The standard input device
stdout
The standard output device
stderr
The standard output device for error messages
stdin is generally associated with the keyboard, while stdout and stderr are associated with the display, unless redirection has been performed using the function freopen() or by the environment in which the program is running.
There is no predefined file structure in C: every file is assumed to contain simply a sequence of bytes. The internal structure of a file is completely left up to the program that uses it.
All read and write operations are applied at the current file position , which is the position of the next character to be read or written, and is always recorded in the FILE structure. When the file is opened, the file position is 0. It is increased by 1 with every character that is read or written. Random file access is achieved by means of functions that adjust the current file position.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Numerical Limits and Number Classification
When working with C's various numeric types, it's important to understand the range of values that each type can hold.
The value ranges of the integer types are documented in the header file limits.h . The constants, listed in Table 1-25, indicate the largest and smallest values that can be represented by the given type.
Table 1-25: Limits of the integer types
Type
Minimum
Maximum
Maximum of the unsigned type
char
CHAR_MIN
CHAR_MAX
UCHAR_MAX
signed char
SCHAR_MIN
SCHAR_MAX
short
SHRT_MIN
SHRT_MAX
USHRT_MAX
int
INT_MIN
INT_MAX
UINT_MAX
long
LONG_MIN
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Mathematical Functions
C supports a variety of useful mathematical functions. Different functions apply to different datatypes. For example, randomization functions apply to integers, whereas trigonometric functions apply to floating-point values.
The mathematical functions for the types int and long are declared in stdlib.h.
int rand( void );
Generates a random number between 0 and RAND_MAX. The constant RAND_MAX has a value of at least 32767, or 215 - 1.
void srand( unsigned n );
Initializes the random number generator with the seed n. After this function has been called, calls to rand() generate a new sequence of random numbers.
int abs( int x );
Returns the absolute value of x.
div_t div( int x, int y );
Divides x by y and stores the integer part of the quotient and the remainder in a structure of type div_t, whose members quot (the quotient) and rem (the remainder) have type int. The type div_t is defined in stdlib.h.
The corresponding (to abs() and div()) functions labs() , llabs() (*), lldiv() (*), and ldiv() are also provided for integers of type long long(*). Furthermore, the functions imaxabs()
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Character Classification and Case Mapping
A number of functions for classifying and changing the case of characters with type char are defined in the header file ctype.h . These functions, whose names begin with is... or to..., accept a one-character argument whose value is between 0 and 255, or EOF.
The is... functions, listed in Table 1-39, test whether the character is a member of a specific category of characters. They return "true," i.e., a non-zero value, if the character is in the given category. If not, the return value is 0, or "false."
Table 1-39: Functions for character classification
Category
Function
Letter
int isalpha( int c );
Lower-case letter
int islower( int c );
Upper-case letter
int isupper( int c );
Decimal digit
int isdigit( int c );
Hexadecimal digit
int isxdigit( int c );
Letter or decimal digit
int isalnum( int c );
Printable character
int isprint( int c );
Printable character other than space ' '
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
String Handling
There is no basic type for strings in C. A string is simply a sequence of characters ending with the string terminator, stored in a char array. A string is represented by a char pointer that points to the first character in the string.
The customary functions for manipulating strings are declared in string.h . Those functions that modify a string return a pointer to the modified string. The functions used to search for a character or a substring return a pointer to the occurrence found, or a null pointer if the search was unsuccessful.
char *strcat( char *s1, const char *s2 );
Appends the string s2 to the end of s1. The first character copied from s2 replaces the string terminator character of s1.
char *strchr( const char *s, int c );
Locates the first occurrence of the character c in the string s.
int strcmp( const char *s1, const char *s2 );
Compares the strings s1 and s2, and returns a value that is greater than, equal to, or less than 0 to indicate whether s1 is greater than, equal to, or less than s2. A string is greater than another if the first character code in it which differs from the corresponding character code in the other string is greater than that character code.
int strcoll( const char *s1, const char *s2 );
Transforms an internal copy of the strings s1 and s2 using the function strxfrm(), then compares them using strcmp() and returns the result.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Searching and Sorting
The following two functions are declared in the header file stdlib.h as general utilities for searching and sorting:
void qsort(void *a, size_t n, size_t size, int (*compare)(const void *,const void *));
Sorts the array a using the quick-sort algorithm. The array is assumed to have n elements whose size is size.
void *bsearch( const void *key, const void *a, size_t n, size_t size, int (*compare)( const void*, const void* ) );
Searches in a sorted array a for the keyword addressed by key, using the binary search algorithm. The array a is assumed to have n array elements whose size is size.
The last parameter to these functions, compare, is a pointer to a function that compares two elements of the array a. Usually this function must be defined by you, the programmer. Its parameters are two pointers to the array elements to be compared. The function must return a value that is less than, equal to, or greater than 0 to indicate whether the first element is less than, equal to, or greater than the second. To search or sort an array of float values, for example, the following comparison function could be specified:
int floatcmp( const void* p1, const void* p2 )
{  float x = *(float *)p1,
         y = *(float *)p2;
    return  x <= y ? ( x < y ? -1 : 0) : 1;
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Memory Block Management
The following functions declared in string.h are used to compare, search, or initialize memory buffers:
void *memchr( const void *buf, int c, size_t n );
Searches the first n bytes of the buffer buf for the first occurrence of the character c.
void *memcmp( const void *s1, const void *s2, size_t n );
Compares the first n bytes in the buffer s1 with the corresponding bytes in the buffer s2. The return value is less than, equal to, or greater than 0 to indicate whether s1 is less than, equal to, or greater than s2.
void *memcpy( void *dest, const void *src, size_t n );
Copies n bytes from the buffer src to the buffer dest.
void *memmove( void *dest, const void *src, size_t n );
Copies n bytes from the buffer src to the buffer dest. In case the buffers overlap, every character is read before another character is written to the same location.
void *memset( void *dest, int c, size_t n );
Fills the first n bytes of the buffer dest with the character c.
The corresponding wmem... functions, for handling buffers of wide characters with type wchar_t, are declared in the header file wchar.h (*).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Dynamic Memory Management
In order to make efficient use of memory, it is important for a program to be able to allocate and release blocks of memory dynamically during execution. The functions for dynamic memory management are declared in the header file stdlib.h .
A successful call to one of the memory allocation functions returns the beginning address of a memory block of the requested size. The return value has the type "pointer to void". The program can then use the allocated block in any way desired. When a block of memory is no longer needed, it should be released. All dynamically allocated memory blocks are automatically released when the program exits.
void *malloc( size_t size );
Allocates a memory block of size bytes.
void *calloc( size_t n, size_t size );