- what exactly happens in memory when int *mypointer; is declared?
Sufficient memory is allocated from the stack to store a memory address. This will be 32 or 64 bits, depending on your OS.
- what does mypointer represent?
mypointer
is a variable on the stack that contains a memory address.
- what does *mypointer represent?
*mypointer
is the actual memory location pointed to by mypointer
.
- when *mypointer = 10; what happens in memory?
The value 10
is stored in the memory location pointed to by mypointer
. If mypointer
contains the memory address 0x00004000
, for example, then the value 10
is stored at that location in memory.
Your example with comments:
int main ()
{
int firstvalue, secondvalue; // declares two integer variables on the stack
int * mypointer; // declares a pointer-to-int variable on the stack
mypointer = &firstvalue; // sets mypointer to the address of firstvalue
*mypointer = 10; // sets the location pointed to by mypointer to 10.
In this case same as firstvalue = 10; because
mypointer contains the address of firstvalue
mypointer = &secondvalue; // sets mypointer to the address of secondvalue
*mypointer = 20; // sets the location pointed to by mypointer to 10.
In this case same as secondvalue = 20; because
mypointer contains the address of secondvalue
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
Try this code and see if that helps:
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
mypointer = &firstvalue;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
*mypointer = 10;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
mypointer = &secondvalue;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "mypointer is pointing to " << mypointer << endl;
return 0;
}