Pointers

From ROBOTC API Guide
Revision as of 20:30, 3 September 2012 by Jwatson (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
General Programming → Pointers


Color Key
Function:
Variable:


Pointers

Pointers are used to 'point' to a variable's memory location, instead of the value stored in that location. Even if the value of the variable changes, its memory location generally stays the same. In the example below, there are three variables; a pointer integer variable called 'pointer', denoted as a pointer by the asterik * preceding its name, an integer variable called 'nopointer', and an integer called 'foo'.
task main()
{
int *pointer;
int nopointer;
int foo=0;
 
pointer=&foo;
nopointer=foo;
 
foo=5;
 
pointer=&foo;
nopointer=foo;
}
Line 7 of the program sets the 'pointer' variable to the memory location of 'foo' (this is done by using the ampersand symbol (&) when setting pointer equal to foo) and line 8 sets the 'nopointer' variable to the value of 'foo'. The Local Variables debug window shows that 'pointer' now has the memory location of foo (0x2D52) while 'nopointer' holds the value of foo (0).
Next, we change the value of 'foo' to 5 and reset the values of 'pointer' and 'nopointer' to foo. The Local Variables window again updates its values to show that nopointer now has the value in foo (5) but the pointer variable has remained unchanged. This is because even though the value of the variable foo has changed, its location in memory has not.

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.