     Next: Complex Up: Arrays Previous: Dynamic Resizing   Contents   Index

### Pointers

A pointer to an array is a variable which points to the data of an array, and behaves as an array itself but does not contain its own data. Pointers can point to the array itself, or to a sub-array of an array with multiple dimensions, or to an offset into the data of a single dimensional array.

The simplest case is a direct assignment to an array.

x[2, 4]
y = x

In this case, the data (held in x) can be accessed through y or x equivalently. In this special case, y is an alias, and the array can be dynamically resized through y or x.

A more interesting case is provided through use of the overloaded `+' operator. For example

x[2, 4]
y = x + 1

In this construct, the offset is into the highest dimension of x, and the return value is the sub-array found at this offset. In the example, y is a ``'' which is located at the address of x[0,1], i.e., y = x[0, 1], y = x[1, 1], y = x[2, 1].

If x is a single dimensional array, y would also be a single dimensional array, but accessing the data through the offset. For example

x
y = x + 10

Then y = x, y = x, etc.

In general references, but not assignments, supplying a smaller number of dimensions to an array will return a sub-array. For example,

x[2, 4]
y = x

This is equivalent to ``y = x + 1'', and y will point to a ``'' at the location of x[0,1].

x[2,4,5]
y = x
z = x[3,4]

The variable y is a ``[2,4]'' located at x[0,0,2]. The variable z is a ``'' located at x[0,3,4].

When a pointer is defined, a reference count is incremented in the pointed-to array. When this reference count is nonzero, the array can not be resized through the dynamic resizing mechanism. The pointers to an array must be reassigned or undefined to allow resizing of the array. Pointers can be reassigned simply by changing them to point to a different array. This can be done arbitrarily.

x[2, 4]
y
z = x + 1
# can't resize x here
z = y
# now ok to resize x

One can undefine a pointer by setting it to 0. Once this is done, the pointer variable has no type, and can actually be reused as another type of variable. It is not an integer unless it is assigned to an integer. The same effect may be obtained by applying the delete operator.

x[2, 4]
y = x + 1
# can't resize x here
y = 0
# now ok to resize x
Print(y)
# will give "y", y has no type and acts like a string
y = 0
Print(y)
# will give "0", y is now an integer

In our initial case,

x[2, 4]
y = x
where the pointer is simply a reference to the array, y is not strictly speaking a pointer, but rather an alias. In particular, this has no limitation on resizing. The array data can be resized through y or x. Thus, arrays can be resized from within function calls if the reference to the array itself is passed to the function, and not a pointer (with an offset).     Next: Complex Up: Arrays Previous: Dynamic Resizing   Contents   Index
Stephen R. Whiteley 2021-01-27