#dynamic 2D array
1 messages · Page 1 of 1 (latest)
write a function that handles the indexing for you, the compiler can only flatten arrays it knows the size of
double indexing requires an indexable type of which the child type is also indexable - that will not play well with a single flat allocation.
I think it's best to define a slice-like structure that is two dimensional:
pub const Slice2D = struct {
ptr: [*]u32,
len_x: usize,
len_y: usize,
pub fn at(self: Slice2D, x: usize, y: usize) *u32 {
return self.ptr + y * len_x + x;
}
};
I highly recommend what @mortal summit said but if you really want the syntax here is a solution
pub fn main() !void {
var arr: [][]u8 = undefined;
const rows: u8 = 5;
const cols: u8 = 4;
const arr_tmp: []u8 = try std.heap.page_allocator.alloc(u8, rows * cols);
arr = try std.heap.page_allocator.alloc([]u8, rows);
for (0..rows * cols) |i| {
arr_tmp[i] = @intCast(i);
}
for (0..rows) |i| {
arr[i] = arr_tmp[i * cols .. (i + 1) * cols];
}
}
you need to manage arr_tmp somewhere and I think an array of array gets you double dereferencing (maybe slow?) but you get to use arr like you want