How to pass arbitrary 2-d array argument: done!
marwk at levels.sait.edu.au
marwk at levels.sait.edu.au
Mon Jan 7 04:46:07 AEST 1991
In article <1991Jan6.052238.16398 at zoo.toronto.edu>, henry at zoo.toronto.edu (Henry Spencer) writes:
> In article <1991Jan6.044056.23028 at noose.ecn.purdue.edu> luj at delta.ecn.purdue.edu (Jun Lu) writes:
>>It would be nice if I can have a "subroutine" which takes arbitrary matrices as
>>arguments and performs some operations on them. The dimensions of the 2-d
>>array are not known a priori...
>
> Can't be done in C. The dimensions of an array, with the exception of the
> first, must be known at compile time.
>
> (Well, "can't be done" is an exaggeration, but what you end up doing is
> cheating, declaring the arguments as pointers and doing the subscript
> arithmetic yourself rather than using [] notation.)
>
> This is generally considered a deficiency, but it is harder to solve than
> it looks. Some compilers have extensions to do it, although most of those
> extensions have problems of one kind or another. There is work being done
> on finding a good solution.
> --
The method is quite straight forward and I have done it but I cannot find the
code at the moment, but I describe its method here.
#define M 4 /* number of rows */
#define N 7 /* number of columns */
int size = sizeof(int) * M * N /* number of bytes required /*
int *a; /* a 2-D array */
a = (int *) malloc(size);
for (i = 0; i < M; ++i) /* set up the matrix */
for (j = 0; j < N; ++j)
a[(i - 1) * M + j) = 10 * (i + 1) + j + 1; /* 11, 12, 13, ...*/
Now the array can be passed to a function and M and (in particular) N are
not known before the call. Simple!
Ray
More information about the Comp.lang.c
mailing list