vim_snippets/CPP/hpc/dmalloc_2d.c.snip

26 lines
577 B
Plaintext
Raw Normal View History

2024-03-21 13:49:58 +01:00
#include <stdlib.h>
double** dmalloc_2d(int m, int n);
void dfree_2d(double **A);
// allocate a double-precision m x n matrix
double** dmalloc_2d(int m, int n) {
if (m <= 0 || n <= 0) return NULL;
double **A = malloc(m * sizeof(double *));
if (A == NULL) return NULL;
A[0] = malloc(m*n*sizeof(double));
if (A[0] == NULL) {
free(A);
return NULL;
}
for (int i = 1; i < m; i++)
A[i] = A[0] + i * n;
return A;
}
// de-allocating memory, allocated with dmalloc_2d
void dfree_2d(double **A) {
free(A[0]);
free(A);
}