Output after using pointers

Can someone explain to me how to track the variables in the code below? It is a practice problem for my programming final and I have no idea what is going on.

Write the output of the following program.

#include <iostream>
using namespace std;
int fun ( int*& p, int* q) {
*p = 12;
p = p+3;
q = p-1;
*q = *(p+1) + *q;
*p += 2;
cout << "p=" << *p << "q=" << *q << "\n";
return (*q)%(*p);
}
int main( ) {
int y[5] = {1,2,3,4,5};
int* p = y;
int *q = new int;
*q = fun ( p, q );
for (int i=0; i<5; i++)
cout << y[i] << " ";
cout << "\np=" << *p << " q=" << *q;
return 0;

}
I just commented the code as I worked through the program. Take a look:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
using namespace std;
int fun(int *&p, int *q) {
   // *p basically equals y[0] (y[0] now equals 12
   *p = 12;
   // Shifts the pointer down 3 (p now points at y[3])
   p = p + 3;
   // q now points at y[2]
   q = p - 1;
   // the value of y[4] + the value of y[2] is added together and set to y[2]
   // y[2] = 5 + 3 (8)
   *q = *(p + 1) + *q;
   // y[3] is incremented by 2
   // y[3] = 6
   *p += 2;
   // displays the output
   cout << "p=" << *p << "q=" << *q << "\n";
   // returns the remainder of the value of y[2] / y[3]
   // 8 / 6 = 2
   return (*q) % (*p);
}
int main() {
   // Creates an array of 5 values, 1-5
   int y[5] = {1, 2, 3, 4, 5};
   // p points to the same location of y (y is technically a pointer)
   int *p = y;
   // creates a new int pointer
   int *q = new int;
   // passes the "array" and the new int pointer to fun and returns it to q
   // the value of q is now 2
   *q = fun(p, q);

   // Prints out the current array of y
   for(int i = 0; i < 5; i++)
      cout << y[i] << " ";

   // displays the values of the two pointers
   cout << "\np=" << *p << " q=" << *q;
   return 0;

}


If you have any more questions about something in particular, feel free to ask. Also, you can use a debugger to see exactly what's happening on each line if you're confused.
Topic archived. No new replies allowed.