pointers to arrays

lmiller at venera.isi.edu.UUCP lmiller at venera.isi.edu.UUCP
Sat Nov 22 05:48:00 AEST 1986


In article <273 at bms-at.UUCP> stuart at 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 at venera.isi.edu



More information about the Comp.lang.c mailing list