Sunday, July 15, 2007

Buffer Pointers

* The Indexes In Array
As we know, the first index of array in C is 0 and the last one is N-1. It seems not good but actually it is very convenient on the calculation of array length without the off-by-one error IN PROGRAMMING. The basic idea is that zero is the first valid index in array while N is the first invalid index after array, thus the length of this array would be equal to (N-0). So it always looks like:
  for (int i=0; i< N; ++i)

* Buffer Pointers
We could apply the same idea to the definitions of buffer pointers. The size of buffer is N and the pointer to buffer is buf. Furthermore we need one pointer, say bufptr, to indicate the usage of this buffer. It is better off to set bufptr to the first unused place. Thus the length of used region is (bufptr-buf) and that of the unused is (N-(bufptr-buf)). The buffer could be filled in simply by *bufptr++. The full condition could be checked by ((bufptr-buf) == N).

This is the typical example with this technique. Pay attention to the updates of pointers:

void bufwrite(char *p, int n)
{
  while (n > 0)
  {
        int k, rem;
        if (bufptr-buf == N)
        {
              flushbuffer();
        }
        rem = N - (bufptr - buf);
        k = n > rem ? rem : n;
        memcpy(bufptr, p, k);
        bufptr += k;
        p += k;
        n -= k;
  }
}

No comments: