Hacker News new | ask | show | jobs
by pingyong 2188 days 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.

1 comments

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.
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.

Because usually if I want to store something I put it inside the box? Not sure how that is contrived.
When you explain floating point numbers you also put them into boxes? No need for that, you can explain them intrinsically, just like pointers.

Moreover, in practice, it is clear to think that you already have your pointer in your hands (e.g. in a register), no need for your pointer to come from the RAM that it is used refers to. This is an unnecessary recursivity.

>When you explain floating point numbers you also put them into boxes?

That makes no sense. If I was explaining floating point numbers with boxes, for whatever reason, I'd put the values inside the boxes, yes. The analogy just doesn't work here, but the analogy for memory makes perfect sense.

>This is an unnecessary recursivity.

No, it's not. Think of a linked list for example. Traversing it makes perfect sense with my analogy: You open the first box, look at the number that's inside, open the box corresponding to that number, look at what number is inside that box, open the next corresponding box, etc. - it all makes immediate and intuitive sense.

If you just start with "open box x" (because x you somehow already know magically because it's already in a register), you haven't really explained much.

Or think of pointers to pointers. With my analogy: Easy! It's just another box which contains the value of the next box. If this concept isn't explained, a pointer to a pointer makes no sense because the pointer value has no corresponding box, hence no address.