[comp.std.c] C puzzle

dfp@cbnewsl.ATT.COM (david.f.prosser) (08/25/89)

In article <404@opusys.UUCP> rlkd@opusys.UUCP (R.L.K.Dattatri) writes:
>Here is a small puzzle.  The program below will compile and run on some
>compilers but will not compile on others.
>
>main()
>{
>	int *p;
>	p = (int *) malloc(1024);

Since there is no visible declaration for malloc(), it must be
assumed to return an int.  Since it actually returns a void *
(equivalent in this case to char *), it is quite possible that
a "garbage" int value is consequently converted to int *.  (For
example, most 68k implementations return pointer values in a
different register than integral values.)

>	test_it(p);
>}
>test_it (x)
>int (*x)[];

A pointer to an int was passed to test_it().  This parameter
declaration is for a pointer to an unspecified-sized array of
int.  These two are not equivalent, even though the number of
indirection necessary to get to an int may be the same.

>/* If a dimension is specified all compilers will accept it */
>{
>	int i;
>	for (i=0; i < 10; ++i)
>		(*x)[i] = i;
>	/* x++; */
>}
>
>The parameter 'x' in test_it without dimensions works on some compilers
>but others complain incomplete array'.
>I can understand that the compiler is trying to guess the size of the rows
>in the array. But that should come only when the commented x++ is used.
>Without the dimension all compilers generated an increment of 'int' size for
>'x++' but with the dimension it was the size of dimension * int size.
>
>Does ANSI specify anything in this regard?

(Follow-up directed to comp.std.c.)

You are correct that the length of the array is only necessary
in this example if the "x++;" statement is included.  Pointers
to unspecified-sized arrays are valid in the pANS.

Existing implementation were of varying minds with respect to
pointers to arrays.  For example, some took a construct such as
``&array_name'' and slapped your hand with a warning stating that
the & was ignored since it was "incorrect".  This is one of the
areas where the pANS has helped the language.

Dave Prosser	...not an official X3J11 answer...

chris@mimsy.UUCP (Chris Torek) (08/25/89)

In article <1614@cbnewsl.ATT.COM> dfp@cbnewsl.ATT.COM (david.f.prosser) writes:
>You are correct that the length of the array is only necessary
>in this example if the "x++;" statement is included.  Pointers
>to unspecified-sized arrays are valid in the pANS.

So they are.  Oops, disregard parts of my previous followup....

(I still think they ought to be an error, although this would prevent
taking the address of an array of unknown size.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris