The House Analogy
|A good analogy for how pointers operate is how street addresses work. When a house is going to be built, contractors must make sure that the land they are going to build the house on is big enough to contain it. Once the house is built it gets its own street address depending on where it is at on the street. Then, no matter who is living in the house, the street address will remain the same.
Likewise, when a variable is being created in a program, the program must make sure that its memory location is large enough to hold the variable. Once the variable is created it gets its own memory address depending on where in memory it is residing. Then, no matter what value is stored in the variable, the memory address will remain the same.
|Creates a pointer named 'ptr' of the integer type. Both the name and the type of variable must be declared, with the name being preceded by an asterisk (*).|
int *ptr; int foo=0; ptr = &foo;
|Creates a pointer named ptr of the integer type, an integer named foo, and sets the memory address of foo to the pointer ptr (using the ampersand, &).|
int *prt; int foo=0; ptr = foo;
|Creates a pointer named ptr of the integer type, an integer named foo, and sets the value stored by foo to the pointer ptr (in this case, the memory address of 0). This can cause errors if not used correctly and for the most part should be avoided.|