Address of array; really structure & [array] passing

VLD/VMB gwyn at BRL.ARPA
Sun Apr 6 11:23:36 AEST 1986


Yes, when you pass a struct as a C function parameter, it must be
copied into a place private to that invocation of the function.  This
indeed can result in high overhead.  Experienced C programmers will
pass pointers to large structs rather than the structs themselves,
when possible.  (In older versions of C, one HAD to do it this way.)

When one invokes "func(object)", all (sizeof object) bytes are
copied before the body of "func" starts executing, except when
"object" is the NAME of an array (which means the same as the address
of the first element of the array) or the name of a function.  To
accomplish a "call by reference", one writes "func(&object)",
which requires that "object" be an lvalue (i.e. have an address).

The best examples of passing actual structs instead of pointers
are probably Rob Pike's Blit data structures:
	typedef struct
		{
		short	x;		/* horizontal */
		short	y;		/* vertical */
		}	Point;
	typedef struct
		{
		Point	origin;		/* upper left corner */
		Point	corner;		/* lower right corner */
		}	Rectangle;
with typical usage:
	Point	a, b;
	jsegment( a, b, F_XOR );
These are passed by value, as a matter of convenience.  For
larger data structures such as Bitmaps, pointers are passed
to functions rather than the actual data.

Another example one often sees is
	typedef struct
		{
		double	real;		/* real part */
		double	imag;		/* imaginary part */
		}	Complex;
with typical usage:
	Complex	a, b, c, CxMul();
	a = CxMul( b, c );
This is probably the largest size struct that should be routinely
passed by value.  Our local implementation of complex arithmetic
uses pointers instead, which isn't quite as convenient.



More information about the Comp.lang.c mailing list