I am busy with pointers at the moment and specifically pointers pointing to different elements in an array when I increment.
When I incremented using ++
everything is fine, but when I incremented using +2
things turned out differently to what I expected.
Let me explain.
In the first instance I set p2 = p1++;
. The result I got there was what I expected, ie. p2
gives the value 2
and p1
gives the value 3
. This is obviously since the initial value of p1
is assigned to p2
and afterwards p1
is incremented by 1, giving a new value for p1
. No problem with that.
However; in the second instance I setp2 = p1+2
. The result I got was not what I expected. The result was p1
gives value of 2
and p2
gives value of 4
. How can this be? Shouldn't, like in the first instance, the initial value of p1
have been assigned to p2
, and then afterwards p1
incremented by 2 and given a new value of 4
?
Then I got thinking a bit. Maybe +2
and ++
have different characteristics. What I mean with this is that when using ++
, in this case, the code is saying (in layman's terms): "Make p2
point to the same address as p1
did at the start, and then let p1
point to the address of the next element". But when using +2
the code is saying: "Go to the element two "blocks" down from p1
and let p2
point to the address of that specific element; BUT DON'T CHANGE THE ADDRESS p1
IS POINTING TO WHILE DOING SO!". And this is what I mean with "they show different characteristics". They don't act in the same manner.
Is my assumption correct?
Also, how do you increment by two(or three or four, etc.) in this instance whilst maintaining the same characteristics as the ++
operator?
Here are some links to sites I researched which dealt with increments. But none of them really address my problem properly. Nor do any other sites. Also, most of them suggest using something like a +=2
to increment by two, which is fine, but that also does not tackle my specific problem.
Could you please explain in the simplest terms possible since I am still new to C++.
Instance One
#include <iostream>
int main()
{
int a[5] = {1,2,3,4,5};
int *p1, *p2;
p1 = &a[1];
p2 = p1++;
std::cout << "Value1: " << *p1 << "\n" << "Value2: " << *p2;
return 0;
}
Output result of instance one (What I expected)
Value1: 3
Value2: 2
Instance Two
#include <iostream>
int main()
{
int a[5] = {1,2,3,4,5};
int *p1, *p2;
p1 = &a[1];
p2 = p1+2;
std::cout << "Value1: " << *p1 << "\n" << "Value2: " << *p2;
return 0;
}
Output result of instance two (NOT what I expected)
Value1: 2
Value2: 4