Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!caip!ut-sally!pyramid!decwrl!sun!guy From: guy@sun.uucp (Guy Harris) Newsgroups: net.lang.c,net.micro.pc,net.unix Subject: Re: My pointer stuff: C caught me again (?) but it has truths in it Message-ID: <4610@sun.uucp> Date: Sun, 29-Jun-86 02:23:01 EDT Article-I.D.: sun.4610 Posted: Sun Jun 29 02:23:01 1986 Date-Received: Mon, 30-Jun-86 04:20:11 EDT References: <1242@ncoast.UUCP> <418@dg_rtp.UUCP> <1267@ncoast.UUCP> <4609@sun.uucp> Organization: Sun Microsystems, Inc. Lines: 58 Xref: watmath net.lang.c:9641 net.micro.pc:8911 net.unix:8447 > 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@sun.com (or guy@sun.arpa)