Hi I came across this bit of C++ code and am trying to learn how pointers operate.
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
My questions are below:
- what exactly happens in memory when
int *mypointer;is declared? - what does
mypointerrepresent? - what does
*mypointerrepresent? - when
*mypointer = 10;what happens in memory?
Sufficient memory is allocated from the stack to store a memory address. This will be 32 or 64 bits, depending on your OS.
mypointeris a variable on the stack that contains a memory address.*mypointeris the actual memory location pointed to bymypointer.The value
10is stored in the memory location pointed to bymypointer. Ifmypointercontains the memory address0x00004000, for example, then the value10is stored at that location in memory.Your example with comments:
Try this code and see if that helps: