Pointers are variables that point to a pointee. Like so:
Behind that deceptively simple definition lurk some pretty hairy pitfalls and subtleties but it’s still the best place to start learning.
In computing, when we’re talking about locations to point to and/or from, we’re really talking about memory addresses. So, given that we’re talking about accessing data at a specified memory location, we should probably start with a basic understanding of how memory is organised and how it works.
If you’re happy with what this diagram represents then you’re good to go, if not you might want a quick tutorial on the basics of memory.
That’s the underlying hardware out of the way, at least for our minimal needs here, so now we can move on to talk about how C implements access to memory in software. If you understand what
int *ptr = &value; means then you can probably skip ahead to the next paragraph but if not, we need to talk about pointer operators and how to read pointer code.
We glossed over the issue of types when we talked about pointer operations but it’s worth delving a little deeper into how C’s type system integrates with pointers. In addition if you step beyond the basic built-in types you need to be aware of how arrays, structs and pointers to pointers operate.
At this point we’ve dealt with the basic mechanics of pointers so we should really step out into the real world and address the perennial question “Why should I use pointers?” and it’s less often encountered brother “Why should I not use pointers?”
Finally let’s address some of the more subtle and underlying ideas around pointers and the terminology associated with them by talking about reference semantics and indirection.