help converting multi-dim arrays

therneau at ur-msbvax.UUCP therneau at ur-msbvax.UUCP
Wed Apr 10 07:26:00 AEST 1985


  A good solution is to use an array of vectors, i.e.,


	static double **data;
		.
		.
		.
		.

	data = calloc(nrows, sizeof(*data));  /*allocate a vector of pointers*/
	for (i=0; i<ncols; i++)
		data[i] = calloc(ncols, sizeof(**data));


The loop allocates storage for each row of the array, and initializes the
the vector of pointers to that storage.  Now the line

		whatever = data[i][j]

in the C program works just fine.  The operation done is two fetches from
memory rather than the (i*ncols + j) of an ordinary array reference; there
is some evidence that the (old) multiplication is slower than the (new)
double memory reference.  As an added bonus, 'data' can be passed to a
subroutine without dimensioning hassles.

    The allocation loop above could certainly be speeded up by doing
only two calloc calls--

	data = calloc(nrows, sizeof(*data));  /*allocate a vector of pointers*/
	dbl_ptr = calloc(nrows*ncols, sizeof(**data));
	for (i=0; i<ncols; i++)  {
		data[i] = dbl_ptr;
		dbl_ptr += ncols;
		}


			Terry Therneau
			Statistics Dept.
			University of Rochester



More information about the Comp.lang.c mailing list