Pointer Operators

Pointers, as you would expect given the not insignificant clue in the name, point to something. Although that’s not necessarily as obviously true as you might think. They point to the memory word at the address specified by the contents of the pointer. This is often referred to as the pointee. That’s all fine and dandy from a conceptual standpoint but how do we get from one to the other in the real world of code?

We have two operators in C: and &. Certainly to begin with the best advice I can give you is to think of as the ‘what’s at’ operator and & as the ‘where is’ operator. You can connect the two thoughts together by thinking of & as the opposite of *. When you get more familiar with these things you’ll want to refer to them by more grown up names, pretty much entirely so you can bill more to your clients; because in fact there’s nothing wrong with the terminology I just gave you.

Terminology aside, if we have the name of a normal, non-pointer variable, we can use the address-of operator & to return the memory address of that variable. Here’s some sample code to illustrate:

You can run the code here if you want to see the output and/or experiment. My output was The address of val is: 0xbfc3ef8c where the 0xbfc3ef8c is in hexadecimal format. Your output address will almost certainly be different. Try checking the output of repeated runs. Do you get the same address each time? What does that tell you about the underlying software and hardware? Is this behaviour likely to be the same on all machines? Try adding more variables and see whether there’s a pattern in their output addresses.

Bear in mind that pointers are just variables too so we can do exactly the same operation on them, even though it might take a bit to wrap your head around:

Here we have &ptr pointing to ptr which contains &val which points to val which contains 1234.

pointer-to-value

Again, have a play with this code. Try creating pointers to pointers to pointers to pointers for example.

You might have noticed that I just skipped over discussion of the * in that code What’s going on there?

Well, we can also go in the opposite direction to &. If you want the big bucks, this is called dereferencing and is the act of getting the value stored at an address, or in other words, the value in the pointee. We can do this using the * operator, also known as the indirection or dereferencing or value-at-address operator, or in our original terminology, it’s the ‘what’s at’ operator.

One final but important note about pointer operators – you need to read pointer code quite carefully until you get used to it. int ptr says that ptr (the thing pointed to by ptr) is an int. int pointedto = *ptr says pointedto is an int that contains the value pointed to by ptr.

Leave a Reply

Your email address will not be published. Required fields are marked *