marwk@levels.sait.edu.au (01/07/91)
In article <1991Jan6.052238.16398@zoo.toronto.edu>, henry@zoo.toronto.edu (Henry Spencer) writes: > In article <1991Jan6.044056.23028@noose.ecn.purdue.edu> luj@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
henry@zoo.toronto.edu (Henry Spencer) (01/08/91)
In article <15805.2787625f@levels.sait.edu.au> marwk@levels.sait.edu.au 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. >> >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. > >int size = sizeof(int) * M * N /* number of bytes required /* > >int *a; /* a 2-D array */ Uh, this isn't a 2D array at all; it's a pointer to a vector of values, and you are doing the address arithmetic yourself to simulate an array. That's quite workable, but it's probably not what the original poster was after. -- If the Space Shuttle was the answer, | Henry Spencer at U of Toronto Zoology what was the question? | henry@zoo.toronto.edu utzoo!henry