[prev] 60 [next]

Pointers and Arrays

An alternative approach to iteration through an array:
  • determine the address of the first element in the array
  • determine the address of the last element in the array
  • set a pointer variable to refer to the first element
  • use pointer arithmetic to move from element to element
  • terminate loop when address exceeds that of last element
Example:

int a[6];
int *p = &a[0];
while (p <= &a[5]) {
    printf("%2d ", *p);
    p++;
}