Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!rutgers!sri-unix!hplabs!sdcrdcf!trwrb!aero!venera.isi.edu!lmiller From: lmiller@venera.isi.edu.UUCP Newsgroups: comp.lang.c Subject: Re: pointers to arrays Message-ID: <1783@venera.isi.edu> Date: Fri, 21-Nov-86 14:48:00 EST Article-I.D.: venera.1783 Posted: Fri Nov 21 14:48:00 1986 Date-Received: Sun, 23-Nov-86 03:27:30 EST References: <273@bms-at.UUCP> Reply-To: lmiller@venera.isi.edu.UUCP (Larry Miller) Organization: ISI, University of So. Calif. Lines: 64 Keywords: What? Why? How? In article <273@bms-at.UUCP> stuart@bms-at.UUCP (Stuart D. Gathman) writes: >I am still confused about several things concerning pointers to arrays. > >There does seem to be such a type, even in K & R. > >1) How does one get such an animal? The only methods I can figure are > > a) a cast: ( type (*)[] ) array_of_type > b) a function returning such a type (but the return must use a cast!) > Paraphrasing myself ("Programming in C", John Wiley 1986): The distinction between an array, and a pointer to its first element, is, for the most part, not useful, IF YOU'RE DEALING WITH A 1D ARRAY. For a 2D array, however, the distinction is important. An example is a 2D array of test score data, the first index selects the student, the second selects the indidividual test: int scores[MAX_STUDENTS][MAX_TESTS]; A routine for computing the average of a particular test (a column), using conventional array subscripting: ---------------------------------------------------------------------- double test_avg(scores, max, n) int scores[][MAX_TESTS], max, n; { long sum = 0; int i; for (i = 0; i < max; i++) sum += scores[i][n]; return (double) sum / max; } ---------------------------------------------------------------------- Now the same routine using a pointer. row_ptr will point to an individual ROW of the matrix (and is thus a pointer to an array), and we'll index off of that to get to the column: double test_avg (scores, max, n) int scores[][MAX_TESTS], max, n; { long sum = 0, i, (*row_ptr)[MAX_TESTS] = scores; /* ptr to first ROW of scores */ for (i = 0; i < max; i++) sum += (*row_ptr++)[n]; return (double) sum / max; } ---------------------------------------------------------------------- What's the difference? The second version was about 25% faster on a VAX 750 using an array with 10,000 rows. The SLOWER the machine, the GREATER this difference will be. Larry Miller lmiller@venera.isi.edu