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
- The block is filled through plain index assignment.
block + 3points at the fourth element and indexes on from there.- Subtracting steps back, and only the original pointer is freed.
Keywords and builtins used here
Intdefformainprintrangevar
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.
Step 2 of 4 in Memory, step 18 of 22 in Parameters & SIMD.