answersLogoWhite

0

Addition of pointers does not work, and here is why...

A pointer is an address in memory. It points to something, such as an integer. If you add 3 times the size of an integer to the pointer, you would be pointing at the third integer past the first integer, assuming that all four of them were lined up nicely in memory. Well, that is the same as an array.

What you CAN do to a pointer is add something to it, subtract something from it, or subtract another pointer from it, with special rules.

Lets say you have a pointer p that points to a[17]. You can refer to the item in question as *p or as a[17], it does not matter. Let says you add 5 to p, p = p+5; Now *p is a reference to a[22], and a[17] can only be referenced as a[17], or *(p-5) if you wanted to get cute.

Subtraction works the same way. p=p-22; means that *p now refers to a[0].

Well what about p=p-123; Now you are in deep doo doo, because you are outside the bounds of a. The same thing would happen if you add too much to p.

You are only allowed to address memory that you properly allocated and for the purpose for which you allocated it. Other memory that you might find "lying around' is not yours to play with and, in fact, using it could cause all sorts of havoc. Only play with memory that you properly allocated.

Now, what about subtraction of pointers. That is legal, and here is why. Lets say you had two pointers p and q, pointing to a[5] and a[17]. If you subtract p from q, you get 12, which is the difference in index between a[5] and a[17]. Note that this ONLY works when the two pointers refer to the same array, otherwise, all bets are off.

User Avatar

Wiki User

14y ago

Still curious? Ask our experts.

Chat with our AI personalities

TaigaTaiga
Every great hero faces trials, and you—yes, YOU—are no exception!
Chat with Taiga
ViviVivi
Your ride-or-die bestie who's seen you through every high and low.
Chat with Vivi
EzraEzra
Faith is not about having all the answers, but learning to ask the right questions.
Chat with Ezra

Add your answer:

Earn +20 pts
Q: Why does addition of two pointers not possible?
Write your answer...
Submit
Still have questions?
magnify glass
imp