Help me cast this!

Chris Torek chris at mimsy.UUCP
Wed May 4 14:59:08 AEST 1988


In article <51875 at sun.uucp> limes at sun.uucp (Greg Limes) writes:
>2) Pointers to indefinite sized arrays are normally kept simply as a
>   pointer to the beginning of the array. This removes one level of
>   indirection in the code, making it easier to read: all your
>   "(*ptr)[rec].field" constructs change into "ptr[rec].field", giving
>   somewhat easier to write, read, and maintain code.

I would (indeed, I did) put it more strongly: it makes it correct.
This is the right idea, in any case.  There are some who claim that
(*p)[i] is somehow more indicative that there is an indefinitely sized
array around somewhere, but I disagree, and side with Greg:  p[i] is
clearer.

One small fix:
>	typedef struct { int len; char *ap; } outrec;
>	int cmp_rec (p, q) outrec *p, *q; { return p->len - q->len; }
	...
>		qsort (output, nrec, sizeof (outrec), cmp_rec);

A shiny new dpANS-conformant compiler will complain here, if you
have written a `#include <stddef.h>' as well, for qsort's final
argument is not a function with two structure pointer arguments,
but rather a function with two (char *) or (void *) arguments
(depending on who you ask: K&R 1st ed., or dpANS).

	int cmp_rec(p, q)
		char *p, *q;
	{

		return (((outrec *)p)->len - ((outrec *)q)->len);
	}

If you do otherwise, on a DG MV series machine, your code will work
about as well as the 4.3BSD `ls' does---which is to say, not at all.
(The Data General has Word Pointers and Byte Pointers, and never the
twain should meet, save by a Cast.)

(And if we *really* get picky we can worry about the call to malloc
when nrec==0. :-) )
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list