I've been trying for a few days now to create structs and then organize their pointers into a 2D array, with no luck. I then tried to re-create my issue in a small test with a 1D array, and I did recreate it. Why cannot I not use an array of pointers outside the scope it was created in? After I leave the scope, all the array indexes point to the last element added to the array. I've been trying lots and lots of different syntax, so if this is goofy, I've probably tried 20 other different ways. I've also tried in 0.10 and 0.11-preview-3312
I feel like this question is similar to another one, but that one doesn't seem to have an answer other than "just hardcode your array initialization" (How to create 2d arrays of containers in zig?)
Does anyone know how to put pointers into an array (compile time length is ok) and then pass the array to a different scope and access all the pointers?
const std = @import("std");
var arr: ?[3]*Foo = [3]*Foo{ undefined, undefined, undefined };
fn range(len: usize) []const void {
return @as([*]void, undefined)[0..len];
}
// const allocator = std.heap.c_allocator;
test "Allocation stays after scope" {
std.debug.print("\n", .{});
if (arr) | *arra | {
for (range(3)) |_, x| {
arra.*[x] = &Foo{ .x = x };
// arra.*[x] = @intToPtr(*Foo, @ptrToInt(&Foo{ .x = x }));
// arra.*[x] = @intToPtr(*Foo, @ptrToInt(&Foo.init( 12*x )));
std.debug.print("idx {}, {?}\n", .{x, arra.*[x]});
}
}
if (arr) | *arra | {
for (range(3)) |_, x| {
std.debug.print("idx {}, {?}\n", .{x, arra.*[x]});
}
}
}
pub const Foo = struct {
const Self = @This();
x: usize,
pub fn init(x:usize) Self {
return Self {
.x = x
};
}
};
The output is
idx 0, arr.Foo{ .x = 0 }
idx 1, arr.Foo{ .x = 1 }
idx 2, arr.Foo{ .x = 2 }
idx 0, arr.Foo{ .x = 2 }
idx 1, arr.Foo{ .x = 2 }
idx 2, arr.Foo{ .x = 2 }