Skip to main content

Pointers

Introduction

Pointer is a special kind of variable that stores an memory address in it. When a pointer stores an memory address that represents another object in the memory, we say that the pointer is pointing to the object. You can access the object indirectly by the pointers pointed to the object, or so-called dereferencing.

Pointers are powerful tools especially operating the low-level resources. But pointers, especially the simple pointers, could be very dangerous if you didn't use them well. The most dangerous accident of using pointers is try to dereference a pointer that points to a object which no longer exist or a pointer that points to null. We call the former dangling pointer and the latter null pointer. Coding with these kinds of pointers could result in bug, vulnerabilities, or even a unrecoverable crash.

Fortunately, Atem also provides ways to prevent most disadvantage of pointers. You can use optional pointers and managed pointers to replace the most use of simple pointers. The flexibility of Atem also enables us to implement garbage collectors or even borrow checkers to ensure further safety.

Simple Pointers

Declaring and Dereferencing Pointers

You can declare a pointer of Int32 by the .& operator:

ptr mutable: Int32.& = undefined;

When you have a pointer, you can now let it point to some objects by assigning their address to the pointer. You can use .@ operator to get some object's address:

var mutable: Int32 = 42;
ptr = var.@;

You can access the pointed object by using dereference operator .* if you are sure the pointer is pointing to it:

println("ptr.*$");  //print 42

Checking Pointer Validity

Managed Pointers

Optional Pointers

Pointer Arithmetic