avoiding explicit array sizes (was: Point me in the right direction)

Tom Stockfisch tps at chem.ucsd.edu
Fri Feb 24 10:43:45 AEST 1989


In article <14647 at ccicpg.UUCP> swine at ccicpg.UUCP (Peter Swain) writes:
>In article <807 at atanasoff.cs.iastate.edu> hascall at atanasoff.cs.iastate.edu (John Hascall) writes:
>	[ .. week-long discussion deleted .. ]
>>>double fund_consts[] = {
>>>	3.14159265,
>>>};

>Try using 
>	#define dim(a)	(sizeof(a)/sizeof(*(a)))

This doesn't work unless the defining declaration of a[] is in the same file.
If it is in the same file, it probably should have been declared static.
Usually "a" must be declared in a header file which cannot have access to
the initialization.  The scheme I use is

	/* header.h */
	# define NELT 20
	extern int	a[NELT];

	/* extern.c */
	# include "header.h"
	int	a[] = { 42, 666, ... };
	/* compiler will complain if sizeof(a)/sizeof(a[0]) is not equal
	 * to NELT, thus ensuring that extern.c and header.h are in sync
	 */

Any file in the project can then get at the dimension of "a" by #include'ing
"header.h".  "extern.c" must NOT be

	int	a[NELT] = {...};

because if you delete a member of the initialization set, NELT becomes out
of sync without the compiler being able to complain.
-- 

|| Tom Stockfisch, UCSD Chemistry	tps at chem.ucsd.edu



More information about the Comp.lang.c mailing list