Pointers (References) in Programming (especially C/C++)

Posted 7 months ago | Originally written on 5 Apr 2011

While learning how to write computer programs in C is quite straightforward for the first few miles, it is not until pointers are conquered that a whole new world opens up. This is not to say that pointers are complicated and hard to learn. Rather, much of the power in C, the possibilities that it's plainness belies, is hidden in the use of pointers. Depending on your teacher, pointers can make sense instantly or can take a lifetime to grasp. I'm in the latter group largely because I cannot say that I've had a teacher but have been fortunate to pick up some ideas in the course of my education.

For the 'pointer-less' programmer, it might not be immediately obvious where pointers may be applied. However, most data structures can only be constructed using pointers. One other common application that I've come to appreciate that depends on pointers is callbacks. A callback is implemented whenever a function takes a function as an argument. Therefore, in the definition (and declaration) of the calling function, its argument will be a pointer to a function.

#include 
...
int the_caller(int (*the_called)(void)); // declaration
...
int the_caller(int (*the_called)(void)) // definition
{
...
printf("%d\n",the_called());
...
return 0;
}
...
int main(void)
{
...
printf("%d\n",the_caller(the_called));
...
return 0;
}

This is possible because the name of a function is a pointer in the same way that the name of an array is a pointer.

It's exciting to see all the powerful things that can be done with pointers. Presently, I'm unwrapping GTK+ which is replete with the use of pointers...