0

Isn't the pattern supposed to be 2 2 3 3 ?

Doubt regarding the inner working of pointers https://code.sololearn.com/cevpej102B21/?ref=app

14th Dec 2018, 3:28 PM
Aniruddha Bagchi
Aniruddha Bagchi - avatar
7 Réponses
+ 3
Step-by-step we have: int array[] = {2,3,4,5}; int *arptr = array; // address of array[0] int value= *arptr; // 2 cout<<value<<"\n"; // 2 value= *arptr++; // 2 (due to post-increment) cout<<value<<"\n"; // 2 value= *arptr; // 3 cout<<value<<"\n"; // 3 value= *++arptr; // 4 (due to pre-increment) cout<<value<<"\n"; // 4
14th Dec 2018, 3:32 PM
Babak
Babak - avatar
+ 3
Yes it does but `after` dereferencing and assigning the current element of the array to `value`, it'd be easy to illustrate it this way value = *arptr; ++arptr;
14th Dec 2018, 4:07 PM
Babak
Babak - avatar
+ 2
If you tracking the program flow `before ` value= *++arptr; you can see that the current address pointed by `arptr` is &array[0] + 1. When `++arptr` gets executed, first, the address gets incremented by 1, then gets dereferenced. So, now the `arptr == &array[0] + 2` and `*arptr == *(&array[0] + 2) == 4`. Actually, for the sake of simplicity, you could write it in two steps like so ++arptr; value= *arptr;
14th Dec 2018, 3:52 PM
Babak
Babak - avatar
+ 2
Haha, glad to help out. 8D
14th Dec 2018, 4:13 PM
Babak
Babak - avatar
+ 1
*++arptr is nothing but *(++arptr) So, before the above operation the pointer gives the address of array[0] , after ++arptr , it should give the address of array[1] , and the value at i.e, *(++arptr) is the value of array[1] , which is 3 not 4. I am maybe at a fundamental error at some point. Help me explain what is it.
14th Dec 2018, 3:40 PM
Aniruddha Bagchi
Aniruddha Bagchi - avatar
+ 1
Sorry for bothering you again.. Does *arptr++ influence the position of the pointer because that is only kind of updation that comes 'before'
14th Dec 2018, 4:02 PM
Aniruddha Bagchi
Aniruddha Bagchi - avatar
+ 1
Wow! Thanks. You guys at Sololearn are really prompt and to the point. Will surely rate it on Play. You saved my 4 marks from tomorrow's test.
14th Dec 2018, 4:12 PM
Aniruddha Bagchi
Aniruddha Bagchi - avatar