#dynamic 2D array

1 messages · Page 1 of 1 (latest)

untold cobalt
#

Is there a way to allocate a M x N array that can be accessed with array syntax, so like array_2d[x][y] = 10

current workaround is to have a single array from const array_2d = allocator.alloc(u32, xsize * ysize); and then resolve indexing with array_2d[x * ysize + y] but thats getting tedious, and has bad readability

mortal summit
#

write a function that handles the indexing for you, the compiler can only flatten arrays it knows the size of

autumn echo
#

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;
    }
};
blazing willow
#

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