A C debugging puzzle

utzoo!decvax!ittvax!tpdcvax!bobvan utzoo!decvax!ittvax!tpdcvax!bobvan
Fri Nov 5 12:13:00 AEST 1982


In the spirit of the recent C puzzles book, here is one to think about:

Given that we have declarations

	#define	SIZE	10

	int	array[SIZE];
	int	i, *ip;

most C programmers recognizes that the following construction clears
the array:

	for (i=0; i<10; i++)
		array[i] = 0;

Most experienced C programmers have learned to recognize the following
construction as a more efficient alternative:

	for (ip=array; ip<&array[10]; ip++)
		*ip = 0;

Using pointers doesn't save much on a machine like a VAX that has
indexing hardware, but makes a world of difference on an 8080.

Now suppose that we extend this to a two dimensional array:

	#define	XSIZE	10
	#define	YSIZE	10

	int	array2d[XSIZE][YSIZE];
	int	*ip;

	for (ip=&array2d[XSIZE][YSIZE]; ip<&array2d[XSIZE][YSIZE]; ip++)
		*ip = 0;

I recently got bitten making this hasty generalization and will feel
better if someone else has to think about for a while to see the
error.  Can you see the bug in the above fragment?  It is a shame that
I have to ask you not to reply to the net.  Mail to me and I'll post a
tally of the answers in a few days.  Comments about the appropriateness
of such puzzles are welcome.

				Bob Van Valzah
				(...!decvax!ittvax!tpdcvax!bobvan)



More information about the Comp.lang.c mailing list