typestar

Pointer arithmetic in Mojo

Adding to a pointer moves it by whole elements, never by bytes.

from std.memory import alloc


def main():
    var block = alloc[Int](6)
    for i in range(6):
        block[i] = i * 10
    var tail = block + 3
    print(tail[0], tail[1], tail[2])
    var back = tail - 2
    print(back[0])
    block.free()

How it works

  1. The block is filled through plain index assignment.
  2. block + 3 points at the fourth element and indexes on from there.
  3. Subtracting steps back, and only the original pointer is freed.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
207
Tokens
69
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 2 of 4 in Memory, step 18 of 22 in Parameters & SIMD.

← Previous Next →

Pointer arithmetic in other languages