#include <alloc.h>
#include "arrays.h"

/*--------------------------------------------------------------------*/
/*                                                                    */
/*  void **alloc_2d_array(int nx,int ny,int psize,int size)           */
/*                                                                    */
/*  dynamically allocates a 2 dimensional array, regardless of size,  */
/*  up to the size of the memory available on the heap, declared as a */
/*  pointer to a pointer of a given type.  psize is sizeof(type *),   */
/*  while size is sizeof(type). the array is of size nx by ny, e.g.   */
/*  z[nx][ny]. the method chosen allows very large array declarations,*/
/*  because the rows of the matrix (z[nx]) do not have to be stored   */
/*  contiguously.                                                     */
/*                                                                    */
/*--------------------------------------------------------------------*/

void **alloc_2d_array(int nx,int ny,int psize,int size)

{
   register int i;
   void **P;

   P = (void **) calloc(nx,psize);
   if (!P) return(P);

   for (i=0; i < nx; i++)
     {
       P[i] = (void *) calloc(ny,size);
       if (!P[i]) return((void **)P[i]);
     }

  return(P);

} /* void **alloc_2d_array() */

/*--------------------------------------------------------------------*/
/*                                                                    */
/*  void free_2d_array(void **P, int nx)                              */
/*                                                                    */
/*  frees a dynamically allocated 2-dimensional array allocate using  */
/*  alloc_2d_array.                                                   */
/*--------------------------------------------------------------------*/

void free_2d_array(void **P,int nx)

{
   register int i;

   for (i=0; i < nx; i++)
     {
       if (P[i] != NULL)
         free(P[i]);
     }

  if (P != NULL)
    free(P);

} /* void free_2d_array() */


