c++ - Why Pointer+Pointer is not allowed but Pointer+integer allowed? -


this question has answer here:

i going through c pointer arithmetic. found pointer addition not allowed pointer + integer allowed.

i thought pointer + pointer not allowed due security reason. if pointer p1 holds 66400 , p2 holds 66444. p1+p2 not allowed p1+66444 allowed. why so?

think way.

address 1: 112, bakers street address 2: 11, nathan road 

why address1 + 3 fine address1 + address2 bad.

(btw address1 + 3 mean 115, backers street)

for same reason multiplication of scalar or address address doesn't make sense.

address1 * 2 // invalid address1 * address2 // invalid 

logically possibly take offset address adding/subtracting adding 2 addresses doesn't make sense because addresses of same variables may different in each run of program. type , value of addition don't make sense.

i thought pointer + pointer not allowed due security reason.

no not allowed because addition of pointers not make sense.

if pointer p1 holds 66400 , p2 holds 66444. p1+p2 not allowed p1+66444 allowed.

you thinking values think of types also. example if a holds 2 kg, , b holds 3 meter, not make sense add them.


there 1 more important thing learn address analogy:

let's there 80 houses on nathan road (analogous arrays in c) , if add 70 address 2 may land in house, garbage bag, or in sea. same reason, if go more 1 past address in array or address before of array behaviour undefined. if dereference address beyond array, behaviour 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 */ 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -