help converting multi-dim arrays

VLD/VMB gwyn at Brl-Vld.ARPA
Fri Apr 12 02:44:04 AEST 1985


Re: large matrix use in C

The closest approach meeting your stated requirements is to vector
matrix rows:

	static	*datap[MAXROWS];	/* init NULL */
	...
	/* access like */ datap[row][col]

With this approach, when setting up the array you have to test
for a null datap[row] and when necessary malloc() a whole row:

	if ( datap[row] == NULL )
		if ( (datap[row] = (double *)malloc( MAXCOLS *
				sizeof(double) )) == NULL )
			/* punt */;
		else
			for ( col = 0; col < MAXCOLS; ++col )
				datap[row][col] = 0.0;

Clearly the only space gain here is if a sizeable fraction of
the rows are never used.  However, there is an enormous speed
gain in some cases by using vectoring instead of having code
generated for index arithmetic (a multiply and add).

To do better with more general sparse arrays, you have to give
up the requirement that array element references look like

	data[row][col]

and instead use macros or functions:

	init_data();	/* sets up structures and fills with 0.0 */
	put_data( row, col, value );	/* stores value in "data" */
	value = get_data( row, col );	/* retrieves value */

Most data structures textbooks discuss algorithms for sparse
arrays.



More information about the Comp.lang.c mailing list