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
Suppose that p has type int*.
|
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. |
What does A[i] abbreviate? Answer
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