0

I am confused with this block of code:

ipPtr = ipPtr + 3; // 5 cout << *ipPtr << endl; 

Why the cout is not 5 but some random large number? can anyone explain to me please. As my understanding I thought the cout << *ipPtr << endl; is pointed to the *ipPtr above it. Am I right ?

#include <iostream> void main(){ using namespace std; int iaArray[] = {1,2,3,4,5}; int* ipPtr = 0; ipPtr = &(iaArray[1]); cout << *ipPtr << endl;//2 ++ipPtr; cout << *ipPtr << endl;//3 ipPtr = ipPtr + 3; //not 5 but random number. cout << *ipPtr << endl; } 
2
  • 5
    You are pointing beyond the end of the array. The array size is 5, and you are pointing at the 6th element that's why you are getting some random number. 2 + 1 + 3 = 6 not 5 :) Commented Jun 19, 2011 at 4:10
  • Any chance you're going to accept one of the answers? Commented Jun 19, 2011 at 18:57

3 Answers 3

8

Because you have incremented the pointer past the end of the array. You seem to have forgotten that you wrote ++ipPtr before adding 3 to it.

 &(iaArray[1]) | iaArray = { 1, 2, 3, 4, 5 } ? | | ++ipPtr ipPtr + 3 
Sign up to request clarification or add additional context in comments.

Comments

0

Because when you add 3 to the pointer it's already on the third position of the array, so it ends up after the last element.

Comments

0
ipPtr = &(iaArray[1]); 

//Pointing to the second position (first one is 0)

++ipPtr; 

//Pointing to the third position

//3 + 3 = 6 ipPtr = ipPtr + 3; 

The array only has 5 positions so it prints whatever is in that memory location not 5 which is in the fifth position.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.