pointers to arrays

braner braner at batcomputer.tn.cornell.edu
Fri Nov 21 05:26:28 AEST 1986


[]

Pointers to arrays come in handy for efficiency in accessing 2-d
arrays.  See K&R about "sparse arrays".  Say you have the "page"
example:

	char page[25][80];

and you want to avoid the slow calculations needed for a direct access
such as "c = page[i][j];".  Set up another array of pointers to lines:

	char *line[25];

Initialize it once to point to the lines:

	for (i=0; i<25; i++)
		line[i] = &page[i][0];

Later you do "c = line[i][j];" - which looks the same but is MUCH faster,
since no multiplication is needed to calculate &line[i][j].  (Well, it
IS necessary to multiply i by sizeof(char *), but hopefully your compiler
is smart enough to do that by a shift, since the size is a power of two -
on most machines.)

- Moshe Braner,  Cornell Univ.



More information about the Comp.lang.c mailing list