Your home address is like a pointer to your house.
You get an address when you decide to build a house at some point in your life (
House* house = new House;
).
You can duplicate/copy this information endlessly and share it with all your friends, but doing that will never build a second house.
It's just a way for your friends to know
where the house is located.
In this context, "pointer arithmetic" becomes a lot simpler too.
Imagine your neighbor is throwing a party and you want to invite your friends.
You can simply tell them "come visit the house
next to Example Lane 21" (
*(house + 1)
).
Pointer arith might seem useless at first but it's basically how arrays work.
Imagine you need to store 100 cars somewhere and lease some construction company to build garages.
They will start building them and, in C/C++-Land, tell you the address of the
first garage.
(
Car* first = malloc(100 * sizeof(Car))
)
Now if you want to drive around in your 28th car, you just need to visit "the garage that is 27 garages away from the first one".
aka
*(first + 27)
or, in the more common form,
first[27]
.
Most people don't believe this at first but
array[index]
is really just defined to be an alias of
*(array + index)
in C.
This is also the reason why arrays usually start at zero.
We already know where the first garage is, so we don't need to add anything to the
array
value to get it.
Also little funfact here:
Because of the way basic math works (1+2 == 2+1) we can actually flip array expressions in C.
26[array]
is valid code and equal to
array[26]