help converting multi-dim arrays

Stanley Friesen friesen at psivax.UUCP
Wed Apr 10 03:55:53 AEST 1985

In article <569 at utcs.UUCP> physics at utcs.UUCP writes:
>From utfyzx!harrison Thu Apr  4 19:53:50 1985
>Received: by utcs.UUCP (4.24/4.7) id AA12979; Thu, 4 Apr 85 19:53:46 est
>Date: Thu, 4 Apr 85 19:53:46 est
>From: utfyzx!harrison
>Apparently-To: physics
>The problem: a large piece of code with a number of arrays, some 
>2 dimensional and a few 3 dimensional, accessed with lines like:
>    for(row=0; row<numrows; row++)
>        for(col=0; col<numcols; col++)
>  [row][col] ...
>The declaration of the matrices, such as
>    static double data[MAXROWS][MAXCOLS]; /* just like FORTRAN */
>is larger than any conceivable set of data it will be asked to 
>deal with, and wastes scads of memory.  So, we want to convert 
>the code to use malloc(3C) to dynamically allocate memory and 
>save all that wasted space. But, we still want to access the 
>matrices as:
> [row][col] ...
>Any ideas?
>Dave Harrison, Dept. of Physics, Univ. of Toronto: ..utzoo!utcs!physics

	Fairly simple. given that you can can calculate the number
of rows and columns desired the following should work:

	char *calloc();
	double **vec;
	int rows, cols, i;

	rows = some stuff;
	cols = other stuff;

	/* Allocate a vector of row pointers of size rows	*/
	vec = (double **)calloc(rows, sizeof(double *));

	/* Allocate a vector of doubles for each row	*/
	for(i = 0; i < rows; i++)
		vec[i] = (double *)calloc(cols, sizeof(double));

And make sure all your routines that use it know how many rows
and columns actually exist and never access past the end.
With this proviso "vec" is usable *exactly* like "data" above.

If you do not have calloc() it is equivalent to malloc(num*size)

				Sarima (Stanley Friesen)

or {ttdica|quad1|bellcore|scgvaxd}!psivax!friesen

More information about the Comp.lang.c mailing list