C puzzle

Chris Torek chris at mimsy.UUCP
Fri Aug 25 03:12:53 AEST 1989


In article <404 at opusys.UUCP> rlkd at 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.

This is a big hint as to the effect that you have written an incorrect
program.  (Many compilers do not catch some forms of incorrect program.)

>main()
>{
>	int *p;
>
>	p = (int *) malloc(1024);
>	test_it(p);
>}
>test_it (x)
>int (*x)[];
>/* If a dimension is specified all compilers will accept it */
>{
>	int i;
>
>	for (i=0; i < 10; ++i)
>		(*x)[i] = i;
>	/* x++; */
>}

Here is what the 4.3BSD-tahoe lint has to say about it.

tt.c:
malloc value used inconsistently	llib-lc(288)  ::  tt.c(5)
test_it, arg. 1 used inconsistently	tt.c(11)  ::  tt.c(6)
malloc value declared inconsistently	llib-lc(288)  ::  tt.c(5)

Alas, it does not catch the declaration `int (*x)[]' itself, only
the fact that it differs from the type of p() in the call two lines
above.

>The parameter 'x' in test_it without dimensions works on some compilers
>but others complain incomplete array'.

The others are correct.  You may not elide the dimensions from []s
except in a few peculiar situations.  Here `T' stands for a simple
type or pointer, structure, or union type:

	extern T array[]; /* refers to an array of unknown size
		which must be defined elsewhere; sizeof(array) is illegal
		(many compilers give 0) */

Or

	T fn(T array[]) { ...  /* declares a pointer! */

>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.

Not necessarily: it is possible that the size and shape of a pointer to
an array depends on the size of the array.  (I have never heard of such
a machine, but one cannot rule it out offhand.)  Note that in normal C
usage, one keeps a pointer to an array element in order to get at an
array, rather than a pointer to the whole array.

>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.

I would expect more compilers to increment x by zero (4BSD PCC does).

>Does ANSI specify anything in this regard?

The proposed standard suggests that programmers not write such declarations.
-- 
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