/* * matalloc: allocates space for a matrix, returns pointer if successful, * NULL if not. The matrix elements are initialized to zero bytes. */ #include "mex.h" #include "matalloc.h" int **matalloc( int rows, int cols) { int **a; /* result pointer */ int i; /* row index */ if( rows < 1 || cols < 1) return 0; /* * first, get space for rows+1 pointers to int */ if( (a = mxMalloc( (rows+1) * sizeof(int *)) ) == 0) return 0; /* * get space for all of the rows, rows*cols int */ if( (a[0] = a[1] = mxCalloc( rows*cols, sizeof(int)) ) == 0) { mxFree(a); return 0; } /* * set the pointers a[1]..a[rows-1] to point to their row */ ++a; for( i = 1; i < rows; i++) a[i] = a[i-1] + cols; return a; } void matfree( int **a) /* free space allocated by matalloc */ { if( a) { mxFree(a[-1]); /* free the matrix data */ mxFree(a-1); /* free the row pointers */ } }