Dynamically allocated multi-dimensional arrays
Judah Greenblatt
judah at uts.uucp
Tue Nov 21 01:12:18 AEST 1989
I've recently been playing around with dynamically allocated
multi-dimensional arrays in C. So far I've found two ways to
handle them:
* As a one-dimensional array, using a macro to do the subscript calculations:
double *a;
a = (double *)malloc(rows * cols * sizeof(double));
#define Sub(a, x, y) ((a)[(x) * cols + (y)])
d = Sub(a, i, j);
This involves no extra space, no extra memory references, but looks ugly.
* As an array of pointers to arrays:
double **a;
a = (double **)malloc(rows * sizeof(double *));
for (i=0; i<rows; i++)
a[i] = (double *)malloc(cols * sizeof(double));
d = a[i][j];
This requires space for a vector of pointers, but allows you to use
the resulting structure exactly as throgh it were a statically-allocated
multi-dimensional array.
(In both cases, you can pack the row and column dimensions along with the
array pointer if necessary.)
What I would like to know is how the existing matrix libraries (linpac,
eispac, imsl) handle varying-sized array arguments in C. (How many of
these libraries have even been translated into C?)
(This problem reminds me of how the IMSL FORTRAN library handled this
case - the compiler did the subscript calculations, but you had to pass
explicit row and column size information to the subroutines.)
Please mail replys to one of the addresses below - I can no longer
afford the time to wade through all of comp.lang.c.
Judah Greenblatt, Bellcore, Morristown, New Jersey, USA, +1-201-829-3059
judah at mrevox.bellcore.com
...!bellcore!mrevox!judah
More information about the Comp.lang.c
mailing list