# CSCI 255 Pointers in C

## Pointers and arrays

• C: Lvalues and Rvalues
• Java: Objects and primitive data types
• `&`address-of operator
• `*`indirection (or dereference) operator
• If `P` is an array of integers, then `P` is a constant pointer to an integer.
• Pointer arithmetic — The follow rules formally apply only when the pointers address lvalues within the same array
• `P[i]` is `*(P+i)`.
• If `P` is a pointer to an integer, then `P+i` is a pointer to the `i`’th integer after the integer referenced by `P`.
• If `P` is a pointer to an integer, then `P-i` is a pointer to the `i`’th integer before the integer referenced by `P`.
• `P++` increments `p` to point to the next integer in memory.
• `P--` decrements `p` to point to the previous integer in memory.
• `NULL` in C is similar to `null` in Java.
• Pascal had pointers: `@P` for `&P` and `P^` for `P*` .

## It only gets worse

Suppose both `P` and `Q` are pointers to integers.

• `P+i` and `P-i` and `P<Q` and `P>Q` and `P++` and `P--` and `P-Q` are formally defined only if the relevant pointers are elements of the same array
• `P + Q` is not allowed for pointers
• `void *` is the type of a generic pointer
• `* (long *) (void *) &P[5]` is weird but implies intent
• `(long) (void *) &P[5]` is `(long) (void *) P + 5 * sizeof(*P)`
• `(long) (void *) &P[5] - (int) (void *) &P[3]` is `2 * sizeof(*P)`

Take a look at the following.

## Trying it out

Take a look at Problem 16 from the Fall 2014 Final exam.