Path: utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!clyde.concordia.ca!thunder.mcrcim.mcgill.edu!snorkelwacker.mit.edu!hsdndev!wuarchive!cs.utexas.edu!uunet!munnari.oz.au!yoyo.aarnet.edu.au!sirius.ucs.adelaide.edu.au!levels!marwk From: marwk@levels.sait.edu.au Newsgroups: comp.lang.c Subject: Re: How to pass arbitrary 2-d array argument: done! Message-ID: <15805.2787625f@levels.sait.edu.au> Date: 6 Jan 91 17:46:07 GMT References: <1991Jan6.044056.23028@noose.ecn.purdue.edu> <1991Jan6.052238.16398@zoo.toronto.edu> Organization: Sth Australian Inst of Technology Lines: 40 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