Notes on Pointers and Arrays
Pointer Arithmetic
Adding an Integer to a Pointer
Adding an integer j to a pointer p yields a pointer to the element j places after one that p points to. More precisely, if p points to the array element a[i], then p + j points to a a[i + j] (provided, of course, that a[i + j] exists).
Subtracting and Integer from a Pointer
If p points to the array element a[i], then p - j points to a[i - j].
Subtracting One Pointer from Another
When one pointer is subtracted from another, the result is the distance (measured in array elements) between the pointers. thus if p points to a[i] and q points to a[j], then p - q equals to i - j.
Compound Literals
Example: int *p = (int []){1,2,3};. (int []){1,2,3} is an unnamed compound literal.
IMPORTANT: in this scenario p has no meta information about the array compound literal because it only points to a first element of an array. This is called array-to-pointer decay. You can still access elements of an array or use pointer arithmetic, however, you have no idea about what the length or an array is and where it ends.
* and ++
We can process arrays with combination of * and ++/-- operators. Here are a some common idioms:
| Expression | Meaning |
|---|---|
*p++ or *(p++) | First, get the value of *p then increment p |
(*p)++ | First, get the value of *p then increment *p |
*++p or *(++p) | First, increment p, then get the value of *p after increment |
++*p or ++(*p) | First, increment *p, then get value of *p after increment |
Array Name as Pointer
In int a[] = {1,2,3} name a can be used as a pointer to first element of an array.
Array Arguments
Array name passed to a function is always treated as a pointer. This means that:
- array is not copied (like an ordinary variable) and is not protected from change
- to protect array from change include
constto array parameter - there is no penalty for passing large array to a function as it is not copied
- for clarity, array parameter may be declared as pointer, e.g.
int *arr
Same as array name can be used as a pointer to first element of an array, pointer to an array can be used as an array name and can be subscripted accordingly.