Pointer in programming language

Box-and-arrow diagrams.

A normal variable is a box, and its value is the contents of the box.

“int y” creates a box which holds ints (and has nothing in it).
“y = 3” puts “3” into the box y.
“x = y” puts the contents of y into the box x.
In the last example, “x” stood for the box itself, but “y” stood for the contents of the box. This is because x was being assigned into, and y was not. Make sure you appreciate this point; it’s the main source of difficulty.

A pointer is an arrow pointing to a box.

“&x” is a nameless arrow pointing to the box x.
“*x” is the contents of the box x points to.
“T* x” (where T is a type) means “x is an arrow that points to boxes containing Ts”
“*x = *y” means “move the contents to the box y points to into the box x points to”
“x = y” (as pointers) makes x point to the box y points to
In the last example, “x” stood for the arrow itself, but “y” stood for the box the arrow y points to, similar to the last example for ordinary variables.

So there are three things to keep track of: the arrow, the box the arrow points to, and the value inside the box. Figure out which one you’re talking about, and you’ll be fine.

Leave a comment