inbinder - 14 days ago 4
C Question

# Clarifying Pointer Notation

In going over some C code I've encountered the following as examples.

``````*(dates +2) I get that this is the 3rd element of the array
``````

.

``````*dates +2   2 added to the value of the 1st element.
``````

Is there a reason for using this notation over:
dates[2]

dates[2] seems clearer.

In `*(dates +2)`, `2` is added to pointer `dates` and then the incremented pointer is dereferenced while in `*dates +2`, pointer `dates` is dereferenced first and then `2` is added to the dereferenced value.

``````        +-------+-------+-------+-------+
|       |       |       |       |
dates   |  2    |   5   |   6   |   10  |
+-------+-------+-------+-------+
x100     x104    x108   x10C
``````

In above expressions `dates` will be converted pointer to the first element, i.e. `dates[0]` of `dates` array. Address of `dates[0]` is `x100`. Therefore,
`*(dates + 2)` means: add `2` units to the base address `x100` and then get the value stored at `x108`. Result will be `6`.
`*dates + 2` means: get the value at base addess `x100` and then add `2` to that value. Result will be `2 + 2 = 4`.

Source (Stackoverflow)