New to Zig. Playing around with some linked lists for fun. I have this code.
const std = @import("std");
const Node = struct {
value: i32,
next: ?*Node,
};
test Node {
const allocator = std.testing.allocator;
const n1: *Node = try allocator.create(Node);
defer allocator.destroy(n1);
n1.value = 10;
const n2: *Node = try allocator.create(Node);
defer allocator.destroy(n2);
n2.value = 20;
// Link n1 and n2.
n1.next = n2;
var cur: ?*Node = n1;
if (cur != null) {
std.debug.print("{d}\n", .{(cur.?).value});
cur = (cur.?).next;
}
if (cur != null) {
std.debug.print("{d}\n", .{(cur.?).value});
cur = (cur.?).next;
}
std.debug.print("cur.isNull={any}\n", .{cur == null});
if (cur != null) {
std.debug.print("{d}\n", .{(cur.?).value});
cur = (cur.?).next;
}
}
I’m trying to iterate through the list, going through Node.next
. Eventually, cur
should be null
and I shouldn’t try to do cur.next
.
However, the weird thing is that after the 2nd if
statement, I would have expected cur
to be null
, but… it’s not? The 3rd if
statement condition is true
, but when I try to access the pointer, it crashes because cur
was null
after all.
$ zig test wat.zig
10
20
cur.isNull=false
General protection exception (no address available)
/home/user/zigidk/src/wat.zig:37:43: 0x1040df5 in decltest.Node (test)
std.debug.print("{d}\n", .{(cur.?).value});
Is there another way I’m supposed to check if my optional is valid?