Pointer error, a error window always pops up

I have a testing program, there is always a error about the pointer, but I can't figure it out:

#include <iostream>

using namespace std;

int main()
{
int a;
int * p1;
int * p2;

int array[3];
p1=&a;
*p1=33;
cout<<p1<<" "<<a<<endl;
p1=p1+3;
*p1=928;
cout<<p1<<" "<<a<<endl;


p2=&array[0];
*p2=999;
cout<<p2<<" "<<array[0]<<endl;
p2=p2+1;
*p2=100;
cout<<p2<<" "<<array[1]<<endl;

cout<<array<<endl;

return 0;
}

If I change the bold part to p1=p1+1 or p1=p1+2, the result will be correct, but there is always a error window pop up, Once I change it to p1=p1+3 or p1=p1+4 etc. the program will run properly. In another word, the number followed by "+" must be larger than 2.

Anybody can tell me the reason?

Thanks a lot.
By doing
p1=p1+ <insert number here>;,
you are changing the pointed-to address, thus when you do:
*p1=<insert number here (again)>
you are assigning the number to absolute garbage.
It works in the second part because all of the memory addresses in an array are in a row, whereas in the first example, there is no set variable (likely) that has its address immediately after a.
As for why it works with numbers > 2, i dunno.

QWERTYman (because my alter alter ego, DVORAKguy, is unnecesarily uncommon)
By doing
p1=p1+ <insert number here>;,
you are changing the pointed-to address, thus when you do:
*p1=<insert number here (again)>
you are assigning the number to absolute garbage.
It works in the second part because all of the memory addresses in an array are in a row, whereas in the first example, there is no set variable (likely) that has its address immediately after a.
As for why it works with numbers > 2, i dunno.


I finally got it, thanks for ur help:-)
Topic archived. No new replies allowed.