Pointers

From ROBOTC API Guide
Revision as of 02:24, 4 September 2012 by Jwatson (Talk | contribs)

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).
Pointers Example One.png
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.
Pointers Example Two.png

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.

Declaring Pointers

int *ptr;
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 (*).

Assigning Pointers

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, 0). This can cause errors if not used correctly and for the most part should be avoided.