Pointers and arrays

This is the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
 #include <iostream>
using namespace std;
int main() {
long n[3] = {100, 200, 300};
long* ref = n;
n[1]++;
cout << n[1] << " " << *ref << endl; //201 100
ref++;
cout << n[1] << " " << *ref << endl; //201 201
*ref = *ref + 1;
cout << n[1] << " " << *ref << endl; //202 202
return 0;
}


As far as I know ref++ points to the next element of the array (here 200) but how does it know it has to be 201? Does it go back to the defintion long* ref = n at line 5 to check that it has to be equal to n?

secondly, why did n[1] on the third cout become 202 when n is only incremented once at n[1]++ at line 6?

Last edited on
I dont know if I understand you right.


1
2
3
secondly, why did n[1] on the third cout become 202 when n is only incremented once at n[1]++ at line 6?

incrementet and added +1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main()
{
   long n[3] = {100, 200, 300};
   long* ref = n;                                     // ref points to n[0]

   n[1]++;                                            // Element n[1] increased by 1; n[] is now { 100, 201, 300 }
   cout << n[1] << " " << *ref << endl;     //201 100

   ref++;                                             // ref now points to n[1] ...
   cout << n[1] << " " << *ref << endl; //201 201     // ... confirmed

   *ref = *ref + 1;                                   // Value of what ref points to (i.e. n[1]) is incremented; n[] now { 100, 202, 300 }
   cout << n[1] << " " << *ref << endl; //202 202     // ... confirmed
}
sorry for the late reply but why does n[1] at line 15 also become 202?
Lastchance has the right answer. The pointer *ref is pointing to the value in your array n[1], not the address. So by adding +1 to the pointer which is pointing to the value, your incrementing by 1.
@muffin123,
n[1] was increased from 201 to 202 on line 14, because ref was pointing to it at the time; *ref is effectively n[1] at that line, so what you do to *ref you are doing to n[1] there.
Registered users can post here. Sign in or register to post.