Allocating a two-dimensional array

daniel edelson daniel at sco.COM
Tue Feb 2 23:54:28 AEST 1988


	In article <22941 at hi.unm.edu> kurt at hi.unm.edu (Kurt Zeilenga) writes:
	>Spencer at ogg.cgrg.ohio-state.edu (PROCEED) writes:
	>>But I can't figure out how to dynamically allocate a two-dimensional 
	>>array of floats.  (I have to have an N by N matrix of floats...)
	>
	>You can not allocate multi-dimensional arrays dynamically.  However,
This statement is wrong. Your example is itself allocating a
multidimensional array dynamically. Perhaps what you intend to say is
that you cannot allocate a multidimensional array in one statement. That
is more nearly accurate.
	>you can do is something like:
	>
	>#define malloc_matrix(p,n,m,t) ((p)=((t)*)malloc((n)*(m)*sizeof(t)))
	>#define matrix(p,n,m,x,y)      ((p)[(n)*(x)+(y)])
	>
	>where
	>	t = element type
	>	p = pointer to type
	>	n,m = dimensions
	>	x,y = indexes
	>
	>malloc_matrix() allocates the space and matrix() is used to pick the
	>element.
	>-- 
	>	Kurt (zeilenga at hc.dspo.gov)

You cannot allocate an array of an anonymous aggregate type. However 
you can allocate an array of a named aggregate type. If your named type
is a vector type, then allocating an array of them yields a
multidimensional array. 

The other way of allocating multidimensional structures in C, since the
language lacks parameterized multidimensional arrays, is to repeatedly
allocate vectors for each dimension of the array. Something like this.

/* Allocate an array of floats */
typedef	float	*floatp;	/* A vector type */
typedef floatp	*array;		/* An array type */

array
allocate(r,c)
unsigned r,c;
{
	int i;
	floatp *A;
	char	*calloc(unsigned, unsigned);

	A=(floatp*)calloc(r,sizeof(floatp));
	for (i=0; i<c; i++)
		A[i]=(float*)calloc(c,sizeof(float));
	return(A);
}

This scheme is disadvantageous in that it takes time proportional to
the number of rows to allocate the array. However, that is probably 
a trivial cost compared to operating on the array elements. Furthermore,
this scheme easily generalizes to arrays of arbitrary dimension. 
The logical and appropriate extension of this is to make an array
type a structure which contains its dimensions. This supports 
general, defensive and transparent programming.

This mechanism also allows A[i] to refer to the i'th row of the
array. When the array is allocated as a continuous block of memory,
A[i] refers to the i'th element. This, of course, stems from C's 
linear storage mapping. 

-- 
uucp:   {uunet|decvax!microsoft|ucbvax!ucscc|ihnp4|amd}!sco!daniel
ARPA:   daniel at sco.COM     Inter:  daniel at saturn.ucsc.edu--------------
pingpong: a dink to the right side with lots of top spin | Disclaimed |
fishing:  flies in morning and evening, day - spinners   | as usual   |



More information about the Comp.lang.c mailing list