22E. Pointer Arithmetic

A pointer is a memory address, which is an integer from the computer processor's perspective. Suppose that p is a pointer of type T *, where T is a type, and values of type T occupy b bytes. If k is an integer, then C++ expression p + k is defined to be memory address p + k*b,

For example, suppose that pointer p points to the first member of a chunk of ints, where an int occupies 4 bytes. Assume that p is memory address 1000. Then p+1 points to the second variable in that chunk; p + 1 is address 1004. Similarly, p+2 points to the third variable, at address 1008.

If p has type T *, then expression p + k also has type T *.


The meaning of p[k]

Notation p[k] abbreviates *(p+k). That is, it

  1. computes the address p+k of the variable at index k in the chunk that p points to, then

  2. gets the variable at index k by following that pointer.


Comparing pointers

You can compare pointers. They work just like integers. If p and q are pointer variables, then expression p < q is true if p holds a smaller memory address than q. Expression p == q is true if p and q hold the same memory address.

Exercises

  1. What does A[i] abbreviate? Answer

  2. Suppose that you are using a 64-bit machine and a variable of type long occupies 8 bytes. If pointer variable p holds memory address 2000, what memory address does expression p+2 yield? Answer

  3. The following function tries to read up to 100 integers from the standard input. So it allocates an array of size 100. But that is wasteful if you only actually read a few integers before hitting the end of the file. So this function decides to give the unused portion of the array back to the heap manager. Does that work?

      int dataSize = 100;
    
      int* readInts()
      {
        int* A = new int[dataSize];
        int i;
    
        for(i = 0; i < dataSize; i++)
        {
          int k = scanf("%i", &(A[i]));
          if(k != 1)
          {
            break;
          }
        }
    
        if(i < dataSize)
        {
          delete [] A + i;
        }
    
        return A;
      }
    
    Answer

  4. Function readInts above wants to read some numbers and return an array containing them. How would its caller know how many integers were read? Answer