can someone explain what is pointer that is being talked about in the lecture videos ? Shimon talks about pointer as being an address but to what ? can someone explain in terms of hack assembly language and a sample code for "pointer" in hack assembly language ?
Pointer is a variable or a data element, which holds the address of some data. For example the code snippet
var Array a, b;
let a = Array.new(10);
let b = a;
creates a new data structure and assigns its address to the variable a. That is, a points to this array.
The next line assigns to b the value of a, which is the address of the array. So b also points to the same array.
In terms of HACK assembly, doing something like:
@x // Stores in register A the address of x
M=D // Stores in R0 the address of x
Now R0 can be thought of as a pointer to x.
Pointers are sometimes called references. They are used in a variate of situations. For example, consider the linked list. Linked list is a structure, where each node holds an element and points to the next node. Here is how it looks conceptually:
To implement this, we'll make each node hold two pieces of information: the data, which is a number in this case, and a pointer to the next node. The last node will hold have a special value in the pointer, to indicate that it's last. Normally this value is 0 and it's called a NULL pointer. Let's say that we put the first node in address 100:
So, the first node contains the value 1 and points to the second node at address 274. The second node contains the value 2 and points to the third node at address 141. The third node contains the value 3 and is the last node in this list, because it points to address 0.
With pointers you can create much more complex data structures. For example, consider what will happen if you put 100 in address 142.