My pointer stuff: C caught me again (?) but it has truths in it

Guy Harris guy at sun.uucp
Sun Jun 29 16:23:01 AEST 1986


> The problem here is that you don't deal with pointers to arrays in the
> following fashion:
> 
> 	int (*pointer_to_array)[];
> 
> 	pointer_to_array =
> 	    (int (*)[]) malloc(number_of_array_elements * sizeof int);
> 	third_element_of_malloced_array = (*pointer_to_array)[2];

Well, after thinking about it, I realized that you *can* deal with pointers
to arrays in that fashion, if you want.  The following bit of code compiles,
runs, and even passes "lint" (modulo "possible pointer alignment problem"
messages):

	main()
	{
		extern char *malloc();
		register int i;
		register int (*pointer_to_array)[];

		pointer_to_array =
		    (int (*)[]) malloc(3 * sizeof(int));

		for (i = 0; i < 3; i++)
			(*pointer_to_array)[i] = i + 4;

			for (i = 0; i < 3; i++)
			printf("array[%d] = %d\n", i, (*pointer_to_array)[i]);
	}

(Note that I got the syntax of the "sizeof" wrong in my previous article -
it should be "sizeof(int)", not "sizeof int".)

It's not customary to do so, however, and you still can't do

	register int (*pointer_to_array)[];
	int array[666];

	pointer_to_array = &array;

since the compiler will bitch about "&array", and probably ignore the "&"
and treat this as

	pointer_to_array = array;

and then bitch that the LHS is of type "pointer to array of 'int'" and the
RHS is of type "pointer to int".

For similar reasons, this trick won't work for a function which takes an
argument which is a pointer to an array, since "lint" (and the compiler,
once function prototypes are generally available) will complain if you try
to pass an array to that function, for the same reason (think of a function
call as containing assignments of the actual parameters to the formal
parameters).
-- 
	Guy Harris
	{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
	guy at sun.com (or guy at sun.arpa)



More information about the Comp.unix mailing list