Pointers in Zig
A single-item pointer doubles a counter in place; .* is the dereference.
const std = @import("std");
fn double(x: *i32) void {
// x.* reaches through the pointer to the value.
x.* *= 2;
}
pub fn main() void {
var count: i32 = 21;
double(&count);
std.debug.print("doubled in place: {d}\n", .{count});
const ptr = &count;
std.debug.print("read through a pointer: {d}\n", .{ptr.*});
}
How it works
x: *i32is a pointer to exactly one integer — no arithmetic, no null.x.* *= 2writes through the pointer;&counttakes the address.- A
const ptrcan still readptr.*— the const is on the binding.
Keywords and builtins used here
constfni32pubvarvoid
The run, in numbers
- Lines
- 15
- Characters to type
- 311
- Tokens
- 92
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 79 seconds.
Step 2 of 3 in Optionals & pointers, step 11 of 27 in Language basics.