Walking the pointer is a simple loop optimization to avoid array index offsets. Lets say you have a loop that looks like this:
int len = 1000;
int *array = (int *)malloc(sizeof(int) * len);
int i;

for(i = 0; i < len; i++)
{
  array[i] = someFunction();
}

Each iteration of this loop needs to grab the pointer value of 'array' and add it to 'i' to get the necessary offset into the array. That consists of an extra add operation that we can get rid of:

int len = 1000;
int *array = (int *)malloc(sizeof(int) * len);
int *ptr;
int i;

ptr = array;
for(i = 0; i < len; i++)
{
  *ptr = someFunction();
  ptr++;
}

This causes the pointer to just move to the next array element, rather than having to calculate the array offset each time.

We make a backup copy of the array pointer so we don't lose the original and use that to access the array. Now the loop consists of the same assignment, but instead of an add, we have a simple increment. Most complilers can optimize the hell out of this.

Ta da!

Log in or register to write something here or to contact authors.