Pointer arithmetic with arrays in C++
I have a little doubt what happens with this pointer, the code is as follows:
#include <iostream>
using namespace std;
void func(int *, int);
int main(int argc, char *argv[])
{
int i, a[10]={1,2,3,2,5};
func(a,4);
for(i=0; i<=4; i++)
cout<<a[i]<<endl;
return 0;
}
void func(int *b,int n)
{
int i;
for(i=0; i<=n; i++)
{
if(b[i]==2) {
b=b+1;
b[i]=b[i]*2;
}
}
}
Precisely in this line of code, it is not very clear to me what is happening:
void func(int *b,int n)
{
int i;
for(i=0; i<=n; i++)
{
if(b[i]==2) {
b=b+1;
b[i]=b[i]*2;
}
}
}
In this line, when i=1
, it's going to enter if
because the value of b[1]
is equal to 2
, but, in this case, the Pointer still points to the value 0
, right? or has it been moving?, because when I run the program, the first and second values do not change, but the third value that is 3
prints it as 6, when it should print 4, right?.
In short, these are the lines that are not very clear to me:
b=b+1;
b[i]=b[i]*2;
Does Scroll and assign the value to b[i]
?
2 answers
The key is the line b = b + 1
, this is where you are advancing the pointer position to the array, so in the next line when you reference b[i]
it is no longer the same element. To illustrate:
When you evaluated b[1]
it was the element with value 2, but after modifying the pointer b[1]
it now references the element with value 3 and this is the one you are duplicating.
When you perform the comparison b[i]
, b
it's still pointed to 1
. You're not wrong.
b[i]
it is equivalent to *(b + i)
, therefore it is returned to the value of the i-th position of the vector, but the value of b
has not changed (b + i
does not imply b += i
). So b
is still pointed to 1
after comparison.
Then, you perform the assignment b = b + 1
, making b
point to 2
.
As b
now points to the 1
, b[1]
(i
still worth 1), it will return a reference to the third element, which you multiply by 2
, obtaining a 6
.