void Test2()
{
int c=8;
int b=7;
int d=9;
int *a;
a = &b;
a+=sizeof(int); //I supposed that *a should points on variable d after this
cout << "b\t" << &b << "\t" << b << endl;
cout << "a\t" << a << "\t" << *a << endl;
cout << "c\t" << &c << "\t" << c << endl;
cout << "d\t" << &d << "\t" << d << endl;
}
I supposed that *a should points on variable d because b and d (as I thought) lie nearby in the stack of local variables. But *a points on another address so *a!=d
My question is why so? Is it the feature of Visual Studio 2010 or something else?
No, it’s a feature of C++ called undefined behavior. You can’t do pointer arithmetics outside an array (or one position over the bound of the array) you own.
You could get this to work by
a += 1becauseais already aint*, so+= 1will make it point to the next integer.a+=sizeof(int)will move itsizeof(int)integers to the right.Again, technically it’s undefined.