Arrays and Pointers

I don't understand why the output is 3,1,0,4 rather than 3,1,undef,3.
Is it because I am wrongly assuming that *pn--; decrements the pointer to memory location not part of the array, thus affecting the rest of the code after it?
The comments are my thoughts.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main(void)
{
	int n[]={0,1,2,3,4,5};
	int* pn=n; //pointer to an int named pn is initialized to the first element of array n, n[0],value 0.
	cout << *(pn+3) << endl; //n[0]+ 3 int sized pieces of data forward in memory to arrive at n[3], value 3.
	cout << *++pn << endl; //n[0]+ 1 int size piece of data forward in memeory to arrive at n[1], value 1.
	*pn--; //decrements the value at pointer pn by 1, not sent to cout.
	cout << *pn << endl << *(pn+4) << endl; // n[-1], value ???? and n[3], value 3.
return 0;
}


EDIT: I think I caught my error, the line
 
*pn--;

decrements the value at n[0], 0 by 1 to -1, but doesn't assign it to anything like this:
 
*pn=*pn--;

so when the next line executes the value of *pn is set back to 0 and its back to pointing at n[0].

Did I catch it?
Last edited on
In line 9 you increased value of pointer, it indicates to trhe first element. So, after line 10, it still indicates to the very beginning.
The output is correct. 3, 1, 0, 4.

pn + 3, is the third element.
++pn is the second element.
--pn is the first element.
pn + 4 is the fourth.

When you do ( pn + 3 ), pn is still pointing to the first location, because you haven't actually assigned anything to pn, i.e pn += 3

You only actually change pn's value twice, line 9 and line 10, which when you cout these, you get 1 then 0.
In line 9 you increased value of pointer, it indicates to trhe first element. So, after line 10, it still indicates to the very beginning.


After line 10, pn will have decremented. Although, if this were run within a cout statement, it would have printed 1 and then decremented.

So the output would have been: 3, 1, 1, 4
Last edited on
Topic archived. No new replies allowed.