int variable[3];
int * firstPointer = &variable;
firstPointer[2] = 3;
//And since firstPointer[0] is in the exact same location as firstPointer.
firstPointer = 6; //firstPointer[0] now equals 6 and vice versa.
int variable[3];
int* firstPointer;
firstPointer = variable; // OK
firstPointer = &variable[0]; // OK (does same thing)
firstPointer = &(*variable); // OK (does same thing)
//firstPointer = &variable; // bad (error)
firstPointer[2] = 3; // OK (same as variable[2] = 3;
// because firstPointer2 points to variable)
firstPointer = 6; // bad -- changes firstPointer to point to
// random garbage. Might throw a compiler
// warning/error depending on the strictness
EDIT
I know this is a dynamic integer. I know this is useful for arrays, but what is the use with normal variables?
It isn't generally useful for normal variables because you can just make a normal variable instead of making a pointer. What it is useful for is dynamic object creation. IE Polymorphism and inheritance:
class Parent
{ /* stuff */ };
class ChildOne : public Parent
{ /* stuff */ };
class ChildTwo : public Parent
{ /* stuff */ };
//---------------------
Parent* MakeObj();
int main()
{
Parent* p = MakeObj(); // get an object from MakeObj
p->DoStuff(); // and do something with it
delete p;
return 0;
}
Parent* MakeObj()
{
// get input from user
int i;
cin >> i;
if(i == 0) // return a different object, depending on what the user selected
returnnew ChildOne;
elsereturnnew ChildTwo;
}
-- if you didn't get into these concepts yet, don't worry about it too much. Just showing that it will be useful later on, even if it's not useful now.
int main()
{
int variable[3];
int* firstPointer;
firstPointer = variable; // OK
firstPointer = &variable[0]; // OK (does same thing)
firstPointer = &(*variable); // OK (does same thing)
firstPointer[2] = 3;
*firstPointer = 6;
}
//firstPointer = &variable; I knew this was wrong, not sure what I was thinkin'