Smart double Matrix

I just came across this rather smart double matrix allocation. I had been doing my double matrix allocation in a very simple allocation.. like this, pretty simple eh? right.


double** create_matrix(int size_x, int size_y)
{
double** matrix;
int i,j;
matrix = (double**)malloc(size_x* sizeof(double*));
for(i = 0;i<size_x;i++) {
matrix[i] = (double*)malloc(size_y* sizeof(double));
}
for( i = 0;i<size_x;i++) {
for( j = 0;j<size_y;j++) {
matrix[i][j] = 0;
}
}

return matrix;
}

I can’t point out the merits or demerits about the code that’s below, I’ll update it as soon as I learn more. :)

<blockquote>/*
* ===  FUNCTION  ======================================================================
*         Name:  calloc_double_matrix
*  Description:  Allocate a dynamic double-matrix of size rows*columns;
*                return a pointer.
* =====================================================================================
*/
double**
calloc_double_matrix ( int rows, int columns )
{
int      i;
double **m;
m     = calloc ( rows, sizeof(double*) );       /* allocate pointer array     */
assert( m != NULL);                             /* abort if allocation failed */
*m    = calloc ( rows*columns, sizeof(double) );/* allocate data array        */
assert(*m != NULL);                             /* abort if allocation failed */
for ( i=1; i<rows; i+=1 )                       /* set pointers               */
m[i]  = m[i-1] + columns;
return m;
}  /* ----------  end of function calloc_double_matrix  ---------- */

/*
* ===  FUNCTION  ======================================================================
*         Name:  free_matrix_double
*  Description:  Free a dynamic double-matrix.
* =====================================================================================
*/
void
free_double_matrix ( double **m )
{
free(*m);                                       /* free data array            */
free( m);                                       /* free pointer array         */
return ;
}  /* ----------  end of function free_double_matrix  ---------- */</blockquote>
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Reddit
  • Slashdot
  • description
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati

Leave a comment

Your comment