help converting multi-dim arrays
Donn Seeley
donn at utah-cs.UUCP
Sun Apr 14 17:19:43 AEST 1985
It's not strictly necessary to have an array of pointers to provide a
multi-dimensional array that varies in size, provided the variation is
limited to one dimension. The following example shows one way to
dynamically allocate a multi-dimensional array:
------------------------------------------------------------------------
# define MAXROWS 10000
# define MAXCOLS 1000
f( nrows )
int nrows;
{
register double (*dp)[MAXROWS][MAXCOLS];
char *malloc();
dp = (double (*)[MAXROWS][MAXCOLS])
malloc( nrows * MAXCOLS * sizeof (double) );
if ( dp == NULL )
bomb( "Out of memory" );
(*dp)[1][0] = 1.0;
...
free( (char *) dp );
return;
}
------------------------------------------------------------------------
I believe this is portable code, going on the basis of section 14.3 of
the C reference manual, but I'd be happy to be corrected if wrong.
(Actually, the main reason I like this example is that it provides a
rare instance of a use for one of the more bizarre C type
declarations...)
Donn Seeley University of Utah CS Dept donn at utah-cs.arpa
40 46' 6"N 111 50' 34"W (801) 581-5668 decvax!utah-cs!donn
More information about the Comp.lang.c
mailing list