home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_11_11 / labrocca / dyn2darr.c next >
C/C++ Source or Header  |  1993-05-22  |  1KB  |  45 lines

  1. /* DYN2DARR.C */
  2.  
  3. /*  Copyright 1993 by P. J. LaBrocca
  4.     All rights reserved.
  5.  
  6.     Compiles with Microsoft C versions 6, 7 & 8 (MS-DOS)
  7.     and Symantec THINK C 5 (Macintosh).
  8. */
  9.  
  10. #include <stdlib.h>
  11.  
  12. /******************
  13.     Allocates a block of memory that can
  14.     be accessed as a two-dimensional
  15.     array using subscript operators.
  16.     Use macro defined in DYN2DARR.H, Dyn2dArray,
  17.     instead of function.
  18. *******************/    
  19. void **dyn2darray( unsigned row, unsigned col, 
  20.                                  unsigned el_size )
  21. {
  22.     unsigned c;
  23.     char *p = NULL;
  24.     void **arr = (void **)
  25.          calloc( row * sizeof( void * ) +  /* for pointers */
  26.            row * col * el_size +           /* for elements */
  27.            2 * sizeof( unsigned ),      /* repetition counts */
  28.            sizeof( char )       );
  29.  
  30.     if( arr == NULL )
  31.         return NULL;
  32.                           /* Store row and col */
  33.     p = (char *) arr + row * sizeof( void * );
  34.     * (unsigned *) p = row;
  35.     p += sizeof( unsigned );    /* p is a pointer to char */
  36.     * (unsigned *) p = col;
  37.     p += sizeof( unsigned );
  38.                           /* Link rows to pointers */
  39.     for( c = 0; c < row; ++c ) {
  40.         arr[c] =  p + ( c * col * el_size) ;
  41.     }
  42.  
  43.     return arr;
  44. }
  45. /* End of File */