Hi,

Can someone explain to me what is going on in the code below as im new to pointers and not quite sure what is going on..In particular, an explanation of the first couple of iterations in the for loops would be helpfull..

Thanks

#include<iostream>
 5 using namespace std;
 6  
 7 int main()
 8 {
 9    int x[5] = {1,2,3,4,5}; 
10    int *q, *p = &x[0]; 
11  
12    //increment all values in the array by 1
13    q = p; 
14    for (int i=0; i<5; i++)
15    {
16       (*q++)++; 
17    }
18 
19    //reset q pointer again
20    q = p; 
21    for (int i=0; i<5; i++)
22    {
23      (*(q+i))++; 
24    }

What's (*q++)++ do?

Well lets look inside the parenthesis at *q++.

This is basically dereferencing the pointer *q and then incrementing the value *q++.
(*q++)++ is incrementing the pointer q.

The second for loop? It does the same thing but uses pointer arithmetic differently to achieve its goals.

Please note - When you add 1 to a pointer you increase its value by one unit of its type. In your case you would add sizeof(int) to your pointer. The compiler is nice enough to do the converting for you, all you have to do is q++ or q + i.

Edited 6 Years Ago by gerard4143: n/a

Thanks for reply,

so on iteration 0, q points to value at address x[0] (*q) i.e 1 and then increments it by 1 (++) to give a value of 2..
then it increments q by 1 => q points to value at address x[1] i.e 2

Am i right here??

When you have

int x[5] = {1,2,3,4,5}; 
int *q = &x[0];

Initially q points to the first element x[0]. When you increment q++ it then points to x[1].

The same can be said for the second for loop.

Initially q points to the first element x[0]. When you add i(i = 1) to it (q + i) it then points to x[1].

Edited 6 Years Ago by gerard4143: n/a

This article has been dead for over six months. Start a new discussion instead.