Code covered by the BSD License  

Highlights from
Pointers Toolbox

from Pointers Toolbox by Ben Petschel
basic functions to work with pointer variables and dynamic data types

Pointers Toolbox

Pointers Toolbox

This demo file shows how one might use the Pointers Toolbox

The Pointers Toolbox emulates the behaviour of pointers in languages such as C/C++.

Pointers are variables that point to slots in memory. Here the "memory" or virtual memory is implemented as a large cell array and the pointers are integers that index into that array. An important difference with C is that the size of the memory slot and the type of variables stored in each slot are irrelevant (within system constraints).

The tools I've provided are fairly basic but should be enough to create virtually any dynamic data structure. The demo below shows how to create a stack as a linked list.

Author: Ben Petschel 31/8/2009

Contents

Basic use of pointers

assign a slot in virtual memory

x = 10;
ptr = malloc(x)
ptr =

     1

read the value of the pointer:

mread(ptr)
ans =

    10

rewrite the value of slot in virtual memory:

mwrite(ptr,11)
mread(ptr)
ans =

    11

clear the memory used by ptr

mfree(ptr)

clear the virtual memory

mwipe

Creating a linked list (stack)

pointer to top of stack

topptr = [];

add to the stack

for i=1:3
  top.value = i;
  top.next = topptr;
  topptr = malloc(top);
end;

read back the values of the stack and free the virtual memory, beginning at the top

while ~isempty(topptr)
  top = mfree(topptr);
  i = top.value
  topptr = top.next;
end;
i =

     3


i =

     2


i =

     1

Contact us at files@mathworks.com