Tip:
Highlight text to annotate it
X
A pointer is a variable that contains the memory address of another variable. We declare
a pointer as we would any other variable, except that we prefix its name with an asterisk
(*). The data type used determines what type of memory it will point to.
If we now create a variable of that same type we can make our pointer point to it prefixing
that variable with an ampersand (&) to retrieve its address. This ampersand is called the
address-of operator. Our pointer p now contains the memory address to the variable i. To get
the address stored in the pointer we simply type its name. And to get the actual value
stored in that address we prefix the name with an asterisk, known as the dereference
operator.
Same thing when writing to the pointer. Without the asterisk the pointer is assigned a new
memory address. And with the asterisk it will update the actual value of the variable it
points to.
If we create another pointer and assign it to p it will then get a copy of p's memory
address. Sometimes however we may want a pointer that can point to another pointer. This is
done by declaring a pointer with two asterisks and then assigning it the address of the pointer
we want it to reference. This way when the address stored in p changes r can follow that
change. Typing r now gives the address of p. Dereferencing r gives the address of i
and dereferencing it again gives the value of i.
One of the main usages of pointers is to allocate dynamic memory. Until now we have only had
as much memory available as we have declared for our variables. If we need any additional
memory we have to use the "new" operator. This operator allows for allocation of global
memory which can only be access through pointers.
An important thing to know about dynamic memory is that it will not be released like the rest
of the programs memory when it's no longer needed. Instead we have to manually release
it with the delete keyword when we're done using it. Forgetting to delete memory that
we've allocated with the new keyword will give our program memory leaks and that memory
will stay allocated even when the program shuts down.