home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!uknet!edcastle!festival!ajmy
- From: ajmy@festival.ed.ac.uk (A Myles)
- Newsgroups: comp.lang.c
- Subject: Re: 2-D Arrays Problem Solved
- Message-ID: <28439@castle.ed.ac.uk>
- Date: 20 Nov 92 09:24:35 GMT
- References: <17514@pitt.UUCP>
- Sender: nntpusr@castle.ed.ac.uk
- Lines: 52
-
- Sorry I missed the start of this thread...
-
- I had this problem recently, and noticed from scrutiny of the as code
- that if you define the array using 2 doses of malloc() (one array
- of pointers, say the rows, to arrays of whatever type you want
- to store, which will be the columns)
-
- (i.e. just like argv)
-
- then the function will expand:
-
- int **foo;
- /* whole buncha mallocs in here */
- foo[bar][qux] = ... etc
-
- correctly by evaluating the expression as (precedence rules)
-
- (foo[bar])[qux]
- ^ ^
- base of element of 1d array
- column
-
- so you trade-off having the array scattered through memory for not
- having to use array[one index * a size + another index] stuff, or defining
- all bar one of the array dimensions - not great if you need dynamic
- array sizing.
- Remember the bounds!!!
-
- Unfortunately, when passing such a beastie to a function, I found
- I sometimes needed to use ***array as the arg. to allow for the fact that
- the original 2-d array was defined as **array, and I wanted to
- set up the array in the function so passed &array to it to allow
- the base address to be loaded into array for use in the calling
- function upon return. (arfle barfle gloop?)
-
- this manifests itself as (in fn)
-
- /* set base of whole shebang to pointer array */
- *_base = (type**)malloc(ONEDIMENSION * sizeof(type*));
- /* allocate pointers to data space */
- (*_base)[element] = (type*)malloc(NEXTDIMENSION * sizeof(type));
- /* fill data */
- (*_base)[x][y] = the actual data;
-
- it seems to work ok, but i can see it all ending in tears...
-
- I haven't actually timed it, but i think the array of array method
- may be faster since it is two look-ups rather than a multiply and
- look-up for those on micro-coded-i-cant-multiply-integers-in-one-clock
- machines, though the allocation will be slower (mallocs)
-
- Andy.
-