sizeof(array)

Steve Summit scs at adam.pika.mit.edu
Tue Aug 22 16:12:17 AEST 1989


In article <1989Aug22.024808.17913 at ctr.columbia.edu> seth at ctr.columbia.edu (Seth Robertson) writes:
>I have a problem in that when I pass an array, it loses track of its size.
 [...passes array to subroutine, then tries to compute sizeof(array).]
>I guess I understand what it is does (only passing the address, not any
>additional information), but how do I get it to do what I want?

Just call sizeof before the call, passing the size to the subroutine:

	printit(testcode, sizeof(testcode) / sizeof(testcode[0]));
	...
	printit(code, nents)
	unsigned long code[];
	int nents;

This may seem slightly clumsy, having to compute sizeof() at
the point of each call (you had wanted to centralize the sizeof
processing in the printit subroutine, and centralization of
common functionality is usually a good idea).  However, the
resultant subroutine is somewhat more general.  For one thing,
I find it's often convenient to define large data structures in
separate source files, referenced at point of use with an
extern declaration.  In this case, I end up with something like

	extern unsigned long testcode[];

in the file making use of the testcode array, and I couldn't
compute sizeof(testcode) (even if I wanted to) for a different
but equally compelling reason.  Therefore, I usually define
another global

	int codesize = sizeof(testcode) / sizeof(testcode[0]);

in the same file in which testcode is defined.  The call is then

	extern unsigned long testcode[];
	extern int codesize;

	printit(testcode, codesize);

Passing in an explicit size to printit() also makes it
useful for printing selected subparts of the array, and for
handling the day when the array size becomes dynamic:

	unsigned long *testcode = NULL;
	int codesize = 0;
	...
	codesize = 23;
	testcode = (unsigned long *)malloc(codesize * sizeof(unsigned long));
	...
	printit(testcode, codesize);

                                            Steve Summit
                                            scs at adam.pika.mit.edu



More information about the Comp.lang.c mailing list