[net.lang.c] How to pass subarrays?

glb@ncsu.UUCP (Griff Bilbro) (05/01/85)

<< Propitiation for the line eating trolls >>

I'm doing a lot of 2D programming lately.  Conceptually everything
behaves like 2D arrays, so I want to access things with 2 indices.
That's easy enough, but I want to pass a window of an array to a sub-
routine so that it looks like the original array except that it's
offset.  I want the subroutine to be able to use negative subscripts.
Here's an illustration:

#define S 20
main()
{
	int	big[S][S],
		AverageAtCenter;

	GenerateArray( big );
	AverageAtCenter = LocalAverage( &big[ S/2 ][ S/2 ] );
	printf( "Average at center is %d\n", AverageAtCenter );
}

LocalAverage( window )
	int	window[S][S],
		result;
{
	result = window[-1][0] + window[0][1] +
		window[1][0] + window[0][-1];
	result /= 4;
	return result;
}

At this point, I don't care about speed.  I need the code to look
like the math.  The code above works, but lint complains.  Why does
lint complain?  How can I make C do the indexing arithmetic the way
I want that lint likes?  It amounts to saying w[i][j] is equivalent
to w[i*S+j].  Can't I declare a argument pointer to index like this?

gwyn@brl-tgr.ARPA (Doug Gwyn <gwyn>) (05/03/85)

> #define S 20
> main()
> {
> 	int	big[S][S],
> 		AverageAtCenter;
> 
> 	GenerateArray( big );
> 	AverageAtCenter = LocalAverage( &big[ S/2 ][ S/2 ] );
> 	printf( "Average at center is %d\n", AverageAtCenter );
> }
> 
> LocalAverage( window )
> 	int	window[S][S],
> 		result;
> {
> 	result = window[-1][0] + window[0][1] +
> 		window[1][0] + window[0][-1];
> 	result /= 4;
> 	return result;
> }

(1) I don't think "result" is declared in the right place.
(2) You're passing an (int *) actual argument to the LocalAverage
function, but you have declared its formal parameter as an SxS array,
which is one level difference of dereferencing.  The formal parameter
is equivalent to
	int	window[][S];
or
	int	(*window)[S];
Because of the way code is generated, you can actually get away
with this type punning in this particular case.