Passing 2-D Arrays of unknown size ?

Wm E Davidsen Jr davidsen at crdos1.crd.ge.COM
Thu Dec 21 07:27:37 AEST 1989


  I don't know of any elegant way, there's a truly ugly way which takes
some of the curse off using an array like that in terms of access
overhead and ugly code. There is a certain overhead at the start of the
execution, so there are tradeoffs.

	/* I typed this by hand - beware! */
	access(array, n, m)
	int array[];
	int n,m;
	{
		int **fake;		/* will act like array[n][m] */
		int work;

		fake = (int *)malloc(m * sizeof(int));
		/* test status here */
		fake[0] = array;
		for (work = 1; work < n; work++) {
			fake[n] = fake[n-1] + m;
		}

		/* now using fake[x][y] gives the same address as
		   array[x][y], if the values of n and m were declared
		 */
		
		/* and don't forget to: */
		free(fake);
	}
	
As I say this is not pretty or clever, but it does tend to make the code
a bit more readable. You can also define a macro to do the multiply, but
that can add a lot of overhead.
-- 
bill davidsen	(davidsen at crdos1.crd.GE.COM -or- uunet!crdgw1!crdos1!davidsen)
"The world is filled with fools. They blindly follow their so-called
'reason' in the face of the church and common sense. Any fool can see
that the world is flat!" - anon



More information about the Comp.lang.c mailing list