Jérôme Belleman
Home  •  Tools  •  Posts  •  Talks  •  Travels  •  Graphics  •  About Me

The Point in C Pointers

4 Sep 2005

If you're learning C and pointers scare you, either because you don't understand them or don't understand their purpose, this pragmatic note may help you.

1 Concept and Purpose

A pointer is a variable that contains the address of another variable. You might ask yourself, then: why not work with the variable itself, rather than referring to it via its address? The Kernighan & Ritchie – as well as most textbooks – will explain that pointers provide a way to more efficiently work with data. Think about passing variables as parameters to a function. If you pass the variable itself, a whole copy of it will be made for the function to work with. Similarly, a function returning a variable will result in returning a whole copy of the value carried by the variable.

That's probably completely OK most of the time, when most our variables are small – minutely small, in fact, when compared to the processing power of modern hardware. But before you know it, you'll get to write programs which will juggle data – variables – weighing megabytes, gigabytes, maybe more. And you'll soon out-scale the fastest hardware available today.

2 Pragmatically Speaking

But before you get to this point, what other uses can you make of pointers? I began accepting and appreciating them when I started developing GTK+ applications. GTK+ – the GIMP Toolkit – is, as the name suggests, the library which was used to build the GIMP user interface. It's been so successful that it was soon used in many other projects, and it's likely most of the graphical programs you use in Linux are based on it, without you even noticing. GTK+ is to graphical user interfaces what Times is to fonts. It's everywhere, so much so that you don't even think about it. It's taken for granted.

GTK+ uses C pointers everywhere, even when the variables in question aren't big. It consistently uses a paradigm so natural that you too, as you're having tremendous fun building user interfaces, will soon start mimicking for your own data, without even thinking about it:

  1. You declare a pointer.
  2. You allocate memory and initialise values for some data with a function called like something_new().
  3. You work with this data passing its pointers as parameters to other functions.
  4. Once done with it, you free the memory allocated for this data with a function called like something_destroy().

When C pointers still made me uncomfortable, diving into GTK+ was the quickest, most satisfying way to embrace them.

3 References