Think this way.
Address 1: 112, Bakers street
Address 2: 11, Nathan road
Why Address1 + 3
is fine but Address1 + Address2
is bad.
(BTW by Address1 + 3
I mean 115, Backers street)
For the same reason multiplication of scalar or an address to another address doesn't make sense.
address1 * 2 // Invalid
address1 * address2 // Invalid
Logically it is possibly to take an offset from an address by adding/subtracting but adding 2 addresses doesn't make sense because addresses of same variables may be different in each run of program. Moreover the type and value of addition don't make any sense.
I thought pointer + pointer is not allowed due to security reason.
No it is not allowed because addition of pointers does not make any sense.
if a pointer say p1
holds 66400
and p2
holds 66444
. now
p1+p2
is not allowed but p1+66444
is allowed.
You are thinking only about values think of their types also. For example if a
holds 2
kg, and b
holds 3
meter, it does not make sense to add them.
There is one more important thing to learn from address analogy:
Let's say there are 80 houses on Nathan road (analogous to arrays in C) and if you add 70
to Address 2
you may land in a house, a garbage bag, or in the sea. For the same reason, if you go more than 1 past the address in array or address before the of array behaviour is undefined. If you dereference any address beyond the array, behaviour is undefined.
int NathanRoad[80] = {...};
int *address1 = &NathanRoad[11];
int *q;
int s;
q = address1 + 3; /* OK */
s = *(address1 + 3); /* OK */
q = address1 + 75; /* Bad */
q = address1 + 69; /* OK */
s = *(address1 + 69); /* Bad */