Path: utzoo!mnetor!uunet!sco!daniel From: daniel@sco.COM (daniel edelson) Newsgroups: comp.lang.c Subject: Re: Allocating a two-dimensional array Message-ID: <298@sysco> Date: 2 Feb 88 13:54:28 GMT References: <1050@ogg.cgrg.ohio-state.edu> <22941@hi.unm.edu> Reply-To: daniel@sco.COM (daniel edelson) Organization: The Santa Cruz Operation, Inc. Lines: 72 In article <22941@hi.unm.edu> kurt@hi.unm.edu (Kurt Zeilenga) writes: >Spencer@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@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