#heap allocate multi-dimensional array

1 messages · Page 1 of 1 (latest)

keen mulch
#

How can i heap allocate for a 2 dimensional array? Im kinda confused.

#

perhaps the rows dimension becomes an arrays of pointers to the corresponding columns array?

deep heart
#

is it correct that you know the row-count and column-count when you want to allocate the array, but not at compile time?

keen mulch
#

Its a 2D array to represent the current screen of the terminal. I did this but im not sure if it will work. ```fn makeScreen(allocator: std.mem.Allocator, terminfo: termInfo) ![][]u8
{
var screen = try allocator.alloc(*[]u8, terminfo.rows);

var i = 0;
while (i != (terminfo.rows - 1)) : (i += 1)
{
    screen[i] = try allocator.alloc(u8, terminfo.columns);
}
return screen;

}```

drowsy bison
#
var arr: [][]u8 = undefined;
arr = try std.heap.page_allocator.alloc([]u8, 5);
for (0..5) |i| {
     arr[i] = try std.heap.page_allocator.alloc(u8, 4);
}

works but I think you can also use ptrcast an allocate once

keen mulch
keen mulch
deep heart
#

I would allocate an array of size terminfo.rows * terminfo.columns. To a single row, you can slice the big array. This has the advantage, that you only have to allocate the array in one allocation function which is faster

keen mulch
drowsy bison
keen mulch
drowsy bison
# keen mulch thx, ill try to build my program on it and tell ya if it worked

good luck. but a @deep heart suggested it is better to allocate once in terms of performance and complexity. You can define a custom structure to not write (i*cols + j) multiple times or you can allocate it one buffer just as suggested and create arr to point to the right elements. Here is a snippet if you want

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) |i| {
  arr[i] = arr_tmp[i*cols .. (i+1)*cols];
}

but of course this uses more memory and needs to dereference twice to access data and you need to free arr_tmp and arr. It might not be a problem for you (I guess) but it is there to consider

#

and sorry for the bad format