[comp.lang.c] dynamically define 2-D array

feng@caen.engin.umich.edu (Liqiang Feng) (10/31/90)

I am trying to dynamically allocate a 2-D array, and I think I need 
to declear a pointer which is the pointer to an array of pointers, and 
the pointers in that array of pointers will serve as the pointers to 
the 2-D array. Is this right? Can anybody give me a very simple example 
how it is done? Thank you very much. 

E-mail: feng@caen.engin.umich.edu

karl@haddock.ima.isc.com (Karl Heuer) (10/31/90)

>I am trying to dynamically allocate a 2-D array...

I have mailed the FAQ to this person; others who have the same problem can
wait for the next repost on the first of the month.  I am posting this note in
a vain attempt to stop the redundant discussion before it starts.

Karl W. Z. Heuer (karl@ima.isc.com or uunet!ima!karl), The Walking Lint

ron@argus.lpl.arizona.edu (Ron Watkins) (10/31/90)

If your question is how to declare such a beastie, try this on for size: (please
note that im just typing this in from my head not from some existing piece of
code);

int	i;
DTYPE	** foo;
...
	foo = (DTYPE **) malloc (NAXIS2 * sizeof (DTYPE *));
	for (i = 0; i < NAXIS2; i++)
	    foo[i] = (DTYPE *) malloc (NAXIS1 * sizeof (DTYPE));
/* OR */
	    * (foo + i) = (DTYPE *) malloc (NAXIS1 * sizeof (DTYPE));

Where:
1) DTYPE is your data type of interest. If you want multiple data type
capability, good luck. Maybe someone would be kind enough to enlighten both
of us on that one.
2) NAXIS1 is the fastest axis (note that you can't go zipping through this
two dimensional space with a pointer dereference like when you normally declare
2-D arrays).
3) NAXIS2 is the slower axis (presumably y?).
I supplied to different approaches for the body of the for loop. Please don't
use BOTH of them. :-)

P.S. If I have totally screwed this thing up, no flames please. Just nicely
tell me that I should go crawl under a rock! Oh and while your doing that,
please do send a proper response to the question at hand.

			_		PEACE!
		      / | \		Ron Watkins
		    /   |   \		ron@argus.lpl.arizona.edu
		   (   /|\   )
		    \ / | \ /
		      \ | /