Search code examples
zig

Convert *const [4][4]f32 to []const [4][4]f32


I have a [4][4]f32 matrix, I would like to create a slice from it, how do I do it?

Here is the example code that should be working if this is possible:

const std = @import("std");

pub fn print_matrix_slices(m: []const [4][4]f32) void {
    for (m) |matrix| {
        print_matrix(matrix);
    }
}

pub fn print_matrix(m: [4][4]f32) void {
    for (m) |row| {
        for (row) |elem| {
            std.debug.print("{d} ", .{ elem });
        }
        std.debug.print("\n", .{});
    }
}

pub fn main() void {
    const matrix = [4][4]f32{
        [4]f32{ 4.0, 3.0, 2.0, 1.0 },
        [4]f32{ 8.0, 7.0, 6.0, 5.0 },
        [4]f32{ 12.0, 11.0, 10.0, 9.0 },
        [4]f32{ 16.0, 15.0, 14.0, 13.0 },
    };

    print_matrix(matrix);

    // print_matrix_slices(matrix); // convert me to slices somehow
}

Solution

  • Use the &.{} syntax. For example:

    print_matrix_slices(&.{ matrix });
    

    You may also find this question relevant.