Appendix C

Some Useful Functions from stdlib.h

The header file “stdlib.h”, which stands for “standard library”, is a mixture of many different types of functions that are useful for day-to-day programming purposes. Unfortunately, not many learners are aware of the wealth of functions that lie here. Broadly, the functions in “stdlib.h” could be classified into five groups:

  • Storage allocation
  • Algorithms
  • Integer functions
  • Text conversion
  • Interacting with the environment

This appendix is an effort to introduce this collection of very useful functions to a new C programmer. This is not an attempt to demonstrate all the functions or all the uses of a particular function; rather, it emphasizes on how to use it in our own programs.

qsort()

As is evident from the name, this is a generic implementation of the quicksort algorithm, used to sort lists of elements. Quicksort is widely regarded as one of the best general-purpose sorting techniques, and thus, is a very useful asset as a library function. The qsort() function is declared as:

 

    void qsort (
        void *base,
        size_t n,
        size_t size,
        int (*cmp) (const void *, const void *)
 );

The function qsort() sorts into ascending order an array, base[0] … base[n-1], of objects each of a size specified by the argument “size”. The compare function should have the format:

 

    int compare ( const void *p1, const void *p2 );

The name of the comparison function can be anything, but the arguments have to be of type void * and the return type has to be int. The function should return:

  • negative value if p1 comes before p2 in sorted array
  • 0 value if p1 and p2 can be placed in any order in the sorted array
  • positive value if p1 comes after p2 in sorted array

Here is a program to demonstrate the use of qsort() to sort a structure of number and string, once by the number and once by the string.

 

   /* qsort.c */
 /* Program to demonstrate the qsort() function found in stdlib.h */
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #define print_NumWord_arr(arr, lo, hi)                         
    {                                                           
      int i;                                                    
      for ( i=lo; i<=hi; ++i )                                  
            printf(“%d	%s
”, (arr+i)->num, (arr+i)->word);    
    }
 typedef struct 
 {
    int num;
    char word[10];
 }  Num Word;
 int compare_int ( const void *pa, const void *pb )
 {
    NumWord a=*(NumWord *)pa;
    NumWord b=*(NumWord *)pb;
    return a.num - b.num;
 }
 int compare_string ( const void *pa, const void *pb )
 {
    NumWord a=*(NumWord *)pa;
    NumWord b=*(NumWord *)pb;
    return strcmp(a.word, b.word);
 }
 int main()
 {
    NumWord arr[5]={
      { 2, “two” },
      { 5, “five” },
      { 1, “one” },
      { 8, “eight” },
      { 7, “seven” }
 };
 puts(“Unsorted array : “);
 print_NumWord_arr(arr, 0, 4);
 qsort(arr, 5, sizeof(NumWord), compare_int);
 puts(“
Sorted by Integer : “);
 print_NumWord_arr(arr, 0, 4);
 qsort(arr, 5, sizeof(NumWord), compare_string);
 puts(“
Sorted by Word : “);
 print_NumWord_arr(arr, 0, 4);
 return 0;
 }

The following is the output of the function:

 

   Unsorted array:
 2      two
 5      five
 1      one
 8      eight
 7      seven

 Sorted by Integer:
 1      one
 2      two 5 five
 7      seven
 8      eight

 Sorted by Word:
 8      eight
 5      five
 1      one
 7      seven
 2      two

bsearch()

 

    void *bsearch (
      const void *key,
      const void *buf,
      size_t n,
      size_t size,
      int (*cmp)(const void *, const void *)
 );

The bsearch() function performs a binary search on the array pointed to by base, which must be sorted before calling the function. It returns a pointer to the first member that matches the key pointed to by key or a NULL pointer, if no element matches the key. The number of elements in the array is specified by n, and the size (in bytes) of each element is described by size. The compare function is of type:

 

    int compare ( const void *key_val, const void *data_val );

It performs the same job as in case of qsort() described previously. The following is a program that demonstrates the use of bsearch() on the structure that we previously used for qsort(). We first sort an array using the qsort() and then use bsearch on it.

 

   /* bsearch.c */
 /* Program to demonstrate the bsearch function found in stdlib.h */
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 typedef struct
 {
      int num;
      char word[10];
 } NumWord;
 int compare_int ( const void *pa, const void *pb )
 {
      NumWord a=*(NumWord *)pa;
      NumWord b=*(NumWord *)pb;
      return a.num - b.num;
 }
 int compare_string ( const void *pa, const void *pb )
 {
      NumWord a=*(NumWord *)pa;
      NumWord b=*(NumWord *)pb;
      return strcmp(a.word, b.word);
 }
 int compare_key_int ( const void *key, const void *data )
 {
      int a=*(int *)key;
      NumWord b=*(NumWord *)data;
      return a-b.num;
 }
 int compare_key_string ( const void *key, const void *data )
 {
      char *a=(char *)key;
      NumWord b=*(NumWord *)data;
      return strcmp(a, b.word);
 }
 int main()
 {
 NumWord arr[5]={
      { 2, “two” }, 
      { 5, “five” }, 
      { 1, “one” }, 
      { 8, “eight” }, 
      { 7, “seven” }
      };
      NumWord *pos;
      int key_num=2;
      char *key_word=“two";
      qsort(arr, 5, sizeof(NumWord), compare_int);
      pos=(NumWord *) bsearch ( &key_num, arr, 5, 
                            sizeof(NumWord), compare_key_int);
      printf(“
%d	found at position %d”, key_num, 
      (pos==NULL) ? -1: pos-arr );
      qsort(arr,5,sizeof(NumWord),compare_string);
      pos=(NumWord *) bsearch ( key_word, arr, 5,
                            sizeof(NumWord), compare_key_string);
      printf(“
”%s”	found at position %d”, key_word,
                            (pos==NULL) ? -1: pos-arr );
      return 0;
 }

The output is as expected:

 

   2        found at position 1
“two”    found at position 4
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset