What is a Pointer?
Every computer has a finite amount of memory where all the variables of your program are stored. Each of these locations has an address just as your home has an address. At this location an object can be stored such as the color of this pages background, the solution to that complex algorithm you wrote, as well as all the intermediate working values. In a language like Ruby, when you create a variable such as
x = 5 the variable
x is a reference to the value
5. Ruby decides where to store that value in memory, Ruby knows where it is stored whenever you call
x, and performs other tasks such as deleting the object out of memory when it is no longer needed. Ruby takes care of all these tasks in the background which is great from a programmers perspective.
That being said, there are advantages of using a language which allows you to interact and manage memory. The primary advantage is efficiency as you are a level closer to machine code and can decide how to manage the memory as you want instead of how the higher level language assumes.
All right, now that we have a little background on memory, let’s talk about pointers. A pointer is simply an object that points to the memory address of another object. To get a better feel for this concept we will use the Go sandbox. Note that the Go language does give you access to pointers but does not require the programmer to manage the memory as it does that on its own.
Figure 1 has a short program that has some boiler plate code up from but then creates a variable
x and assigns it the value of
31 at line 6. It then creates a variable
x_pointer which is pointer to the memory address of the value of
x which is
31 by using the
& operator. From this point the program simply prints the memory address as well as the value at that memory address by adding the
* operator. Finally this program changes the value of
x via the variable directly and through the pointer using the
As you can see from the program output in Figure 2, the memory address does not change even though the value at that address is being updated several times. It’s also seen that the value can be update through the variable itself or the pointer. While we have only dipped our toes into what you can do with pointers and their importance, I hope this helps you add one more brick to your understanding of programming and computers in general.