int main()
{
int x=10;
cout<<"value of x: "<<x<<endl;
cout<<"address of x: "<<&x<<endl;
int *p;
p=&x;
cout<<"value of p: "<<p<<endl;
cout<<"address of p: "<<&p<<endl;
cout<<"pointer of p: "<<*p<<endl;
cout<<"\n"<<"ADDING"<<"\n\n";
p=p+2;
cout<<"value of p: "<<p<<endl;
cout<<"address of p: "<<&p<<endl;
cout<<"pointer of p: "<<*p<<endl;
return 0;
}
In the above code i am adding a constant number to a pointer p,but if i try to add 2 pointers then i get an error that it is not allowed.
The reason that i understood of not adding 2 pointers is that it could result in a overflow and crash the code.
But if i wanted to crash the code then i could have added a larger number to the pointer like below:
int main()
{
int x=10;
cout<<"value of x: "<<x<<endl;
cout<<"address of x: "<<&x<<endl;
int *p;
p=&x;
cout<<"value of p: "<<p<<endl;
cout<<"address of p: "<<&p<<endl;
cout<<"pointer of p: "<<*p<<endl;
cout<<"\n"<<"ADDING"<<"\n\n";
p=p+10000000000000000;
cout<<"value of p: "<<p<<endl;
cout<<"address of p: "<<&p<<endl;
cout<<"pointer of p: "<<*p<<endl;
return 0;
}
Thus the above code would crash, if crashing was the reason then why are we allowed to even add a constant to a pointer.