20D. Pointer Arithmetic

Pointer arithmetic

Suppose that p is a pointer of type T *, where T is a type. Keep in mind that a pointer is a memory address, which is just an integer from the computer processor's perspective.

If k is an integer, then C++ expression p + k is defined to be memory address p + k*sizeof(T ), where sizeof(T ) is the number of bytes that something of type T occupies.

For example, suppose that pointer p points to the first member of a chunk of ints, where an int occupies 4 bytes. Let's 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. By definition, p + k is computed as memory address p + 4k, when p has type int*.

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


p[k] abbreviates *(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 is pointed to by p, then

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

Suppose that p has type int*.

  1. p+1 also has type int*.

  2. Recall that, if p has type T *, then expression *p has type T. Since p+1 has type int*, expression *(p+1) has type int.

  3. Since p[1] abbreviates *(p+1), expression p[1] must have type int. It is the variable at index 1 in the array pointed to by p.


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