Zig Pointers
A pointer is a value that refers to another value instead of holding a copy. Reading through the pointer reaches the original value.
A pointer reads the original value
&score makes a pointer to score. Printing ptr.* shows the value stored in score.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var score: i32 = 10;
const ptr = &score;
try out.print("{d}\n", .{ptr.*});
try out.print("{d}\n", .{score});
}Writing through a pointer changes the original
The assignment writes through ptr into score. Printing score proves the original changed.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var score: i32 = 10;
const ptr = &score;
ptr.* = 25;
try out.print("{d}\n", .{score});
try out.print("{d}\n", .{ptr.*});
}Two pointers can share one value
Both pointers refer to count. A write through one shows up when the other reads.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var count: i32 = 1;
const a = &count;
const b = &count;
a.* += 5;
try out.print("{d}\n", .{b.*});
try out.print("{d}\n", .{count});
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var health: i32 = 50;
const ptr = &health;
try out.print("{d}\n", .{ptr.*});
ptr.* -= 20;
try out.print("{d}\n", .{health});
ptr.* = 100;
try out.print("{d}\n", .{ptr.*});
}Key points
- Address of: &x makes a pointer to the variable x.
- Pointer type: a pointer to one i32 has the type *i32.
- Dereference: ptr.* reads the value the pointer refers to, called the pointee.
- Write through: ptr.* = 9 stores 9 in the original variable.
- Const pointee: a *const i32 pointer can read its pointee but cannot write through it.
In this example, ptr refers to health, so the first print through ptr.* shows 50. Subtracting 20 through the pointer drops health to 30. The last assignment stores 100 through the pointer, and the final print reads it back.
Note
this course prints pointees only, because an address value changes from run to run.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
After var x: i32 = 3; and const p = &x;, what does p.* = 9; do?