void main() { int **A;
A = allocate_mat(x,y);
// EXAMPLE: A[0][0] = 1;
free_mat(A, x, y); }
int **allocate_mat(int a, int b) { int m, o; int **mat;
/* allcoate array of pointers */ mat = (int**)malloc(sizeof(int*)*a); if (mat == NULL) return NULL;
/* allocate the rows */ for (m = 0; m < a; ++m) { mat[m] = (int*)malloc(sizeof(int)*b);
/* if no memory to allocate row, free everything till now */ if (mat[m] == NULL) { for (o = 0; o < i; ++j) free(mat[o]); free(mat); return NULL; } } return mat; }
/* free the memory in the end */ void free_mat(int **mat, int a, int b) { int m; if (mat == NULL) return; for (m = 0; m < a; ++m) free(mat[m]); free(mat); }
|