Printing an array with Pointer = Backwards

I'm trying to print an array with "Pointer Arithmetic" but it's coming out backwards.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include <iostream>
int main(void)
{
	int j[] = {5, 2};
	int* pJ = j; //&j[0]; // Should point to the first element in the array j.

	std::cout << *pJ << "\n" << *pJ++ << std::endl; // This prints 2, 5 instead of the expected 5, 2.

for(int i = 0; i < sizeof(j)/4; i++)
		std::cout << j[i] << std::endl; // This prints the array correctly.


return 0;
}


Also if *pJ is pointing to 2 at position j[1] then wouldn't incrementing the pointer *pJ++ go to j[2] (A non existent location?)

Thanks for your help.
*pJ and *pJ++ may be evaluated in any order on line 7, and results in undefined behavior.

Try:

std::cout << *pJ << "\n" << *(pJ+1) << std::endl ;
That works but I'm still not clear on how the order of operations changed from your line to mine. Is it due to the parentheses?
In yours, you modify the pointer. In mine, the pointer is not modified, so the order in which the expressions are evaluated makes no difference.
Topic archived. No new replies allowed.