Pointers to arrays (Mike Newton's problem)

Gordon A. Moffett gam at amdahl.UUCP
Thu Nov 15 09:17:59 AEST 1984


> From:  Mike Newton <newton at cit-vax.ARPA>
> 
> 	One warning in regards to the Amdahl (UTS) C compiler:  variables 
> defined like:		
> 
> float (*f)[3];		(the parenthesis around the *f are IMPORTANT
> 			 and probably ignored by the compiler!).
> 
> 	will NOT work correctly.  For example in the following program:
> 
> char *c;
> float (*f)[3];
> main() {
> 	f = (float (*)[3]) c;
> }
> 
> which should cause a direct copy from c to f instead causes a derfernce.
> 	
> 	They have been notified, and agree that there is a problem.  Hopefully
> a fix will come soon!

[ the following is part of a letter sent to Mike, included here for
  general edification.  The author is John Marshall (amdahl!jlm) ]

...[T]he program you reference:

char *c;
float (*f)[3];
main() {
	f = (float(*)[3]) c;
}

generates the correct code of assigning the value of c to f.
So your statement that the compiler ignored the * in parenthesis
and that c was dereferenced is not correct. The (float(*)[3]) is
merely a cast and doesn't affect code generation at all.
Of course the value received by f is zero since c was never assigned
a value.

There is, however, a problem in the UTS compiler with a pointer to
an array declared as (*f)[]:  when it is used as an rvalue,
it has one too many indirections.  [ Your original program ],
I believe, included a reference to (*f)[n], which caused an
addressability error on UTS.  This was the statement that generated
erroneous code, and the reason for the bug was that the compiler
generated code as if f had been declared as float **f.

The problem indeed has been fixed.

I am curious though as to why f was declared in this way rather than
as
	float *f;

It generates the same storage allocation and references as your
declaration.  Remember that

	float (*f)[3];

does NOT allocate space for an array!  It allocates space for a
pointer to a float just as

	float *f;

does.

The following are equivalent:

	float (*f)[3];
	float x;
	char *c;
	f = (float (*)[3]) c;
	x = (*f)[2];

	float *f;
	float x;
	char *c;
	f = (float *) c;
	x = f[2];

-- John Marshall   amdahl!jlm
-- 
Gordon A. Moffett		...!{ihnp4,hplabs,amd,nsc}!amdahl!gam

37 22'50" N / 122 59'12" W	[ This is just me talking. ]


-- 
Gordon A. Moffett		...!{ihnp4,hplabs,amd,nsc}!amdahl!gam

37 22'50" N / 122 59'12" W	[ This is just me talking. ]



More information about the Comp.lang.c mailing list