top | item 23550150

(no title)

pingyong | 5 years ago

I've always explained it to people like this: Imagine a big cabinet, like a bunch of safe-deposit boxes in a bank. Each box has an unique number written on it, and the boxes are simply numbered 0 to 99. Now when you open a box, you find a piece of paper in it with a number between 0 to 99. It tells you which box to open next - so it points to another box. That's a pointer.

Seems to work pretty well, at least for conveying the basic idea of pointers and dereferencing.

discuss

order

enriquto|5 years ago

But why do you need to mention that this number is inside a box? It seems strangely contrived. Even if the number was outside the box it would be a pointer, it has nothing to do with being in the box.

cillian64|5 years ago

Because usually a pointer is stored in memory in exactly the same way as the things it points to.

Another useful feature of this abstraction is that if you open a box and find a number you don't know whether it's a pointer to another box or whether the number means something else. This demonstrates how, at least in C, your types aren't stored in memory along with the values and you need something else to tell you how to interpret the value you find at an address.

pingyong|5 years ago

Because usually if I want to store something I put it inside the box? Not sure how that is contrived.