Help me cast this!

Stephen J. Friedl friedl at vsi.UUCP
Tue May 3 16:53:20 AEST 1988


In article <294 at fedeva.UUCP>, wrd3156 at fedeva.UUCP (Bill Daniels) writes:
>
> [nonessential lines deleted here]
> 
> How do I cast the malloc() in line 12 of the following program to avoid 
> the lint cries of "warning: illegal pointer combination" et al?
> 
> main()	
> {
> char	*malloc();
>
> 	struct outfile {
> 		int j;
> 		int k;
> 	} (*output)[];
> 
> 	output = malloc(sizeof(struct outfile) * 3);

Some casts defy obvious attempts, and this is one of them.

First, declare an abstract variable (I always use "foo") of the
same type you want to cast.  We want to say "foo is a pointer to
an array of struct outfile", so it would be:

	struct outfile (*foo)[]

This is just an ordinary variable, and it's the same declaration
as "output" above.  To turn this into a cast, drop the "foo" and
put parens around the whole thing:

	(struct outfile (*)[])
                         ^^_________ foo *was* between here

This is the "obvious" proper cast.  Think how this works on others:

	the variable is...	abstract decl	  cast
	------------------	-------------	--------
	int			int foo		(int)
	ptr to char		char *foo	(char *)
	ptr to fcn rtn int	int (*foo)()	(int (*)())

In any valid cast, there is exactly one place where the abstract
variable would fit, and after a while you can get the hang of
where it goes.

-- 
Steve Friedl      V-Systems, Inc. (714) 545-6442       3B2-kind-of-guy
friedl at vsi.com      {backbones}!vsi.com!friedl      attmail!vsi!friedl



More information about the Comp.lang.c mailing list