#C# style multi-dimensional indexing?
1 messages · Page 1 of 1 (latest)
what type is arr in your c# example?
if you want to, say, make an object that acts like a 2d array but actually stores the values in a flat array and computes indices, then you'd need a struct with something like
pub fn get(self: *Self, col: usize, row: usize) *T {
return &self.storage[row * self.width + col];
}
what does arr[x, y] do then
how does an int array know where coordinates (x, y) should be stored
does it have a width and height?
then do this
C# has multi-dimensional arrays, T[,] - they can't use T[][] because that's a jagged array.
in Zig we don't have this problem since array types include their lengths.
arr[x][y] will work just fine in Zig
does every array in c# have this??? or is it a different type
that is somewhat surprising to me
those mean the same thing.
the C# version and the Zig version both calculate an offset into the sequence in the same manner
basically zig doesn't have syntax for multi dimension array and you have to create one for yourself 🤷♂️
that's since Zig has no need for those.
they exist in C# for the sole purpose of making sure each sub-array has the same length
(contrast with jagged arrays)
If you allocate your arrays on the heap and plan on regrowing them it usually makes more sense to store the width and height and do arithmetic with those directly rather than allocating nested buffers. However, if your arrays are of a static size it makes sense to use nested arrays since, at compile time, Zig will produce essentially the same code as C#, so long as you don't need jagged arrays.
if your array's length is runtime known, you should probably go with @sonic wren's solution