Trying to populate 2d array with struct. builds fine, error on run

Hello! I’m new to Zig. Trying to have fun with raylib.
My code builds fine, why does it fail on run?

const Cell = struct {
    cell: Celltype,
    color: rl.Color,
    velocity: f32,
    density: f32,
    alive: bool,
    changed: bool,
};

const Grid = struct {
    list2d: [screenWidth][screenHeight]Cell,

    pub fn init_grid() Grid {
        return Grid{
            .list2d = [_][screenHeight]Cell{[_]Cell{.{
                .cell = Celltype.EMPTY,
                .color = rl.Color.black,
                .velocity = 0.0,
                .density = 0.0,
                .alive = false,
                .changed = false,
            }} ** screenHeight} ** screenWidth,
        };
    }
};

in main function:

const grid = Grid.init_grid();

Build Summary: 4/6 steps succeeded; 1 failed (disable with --summary none)
run transitive failure
└─ run pixels failure
error: the following build command failed with exit code 1:

Isn’t this just stackoverflow? Just because you can initialize statically, does not mean it’s a good idea.

3 Likes

Hello @vruks
Welcome to ziggit :slight_smile:

The simplest way to run a program is by entering the path of the program in the command line. After building, the executable is located at zig-out/bin. The following command runs the program pixels:

> zig-out/bin/pixels

Add the following code to display, when compiling, the size–in bytes–of the Grid.

comptime {
    @compileLog(@sizeOf(Grid));
}

If the size of Grid is bigger than 16MiB then it is a stack overflow.

2 Likes

Oh, thank you so much! :slight_smile:

1 Like

You can instead allocate the 2d array on the heap:

1 Like