Initialization problem regarding pointer

For engine-technical reasons I use an external buffer for moves / state and a pointer in Position.
Now I composed the buffer and the position together in Game.

There is a problem with the state pointer.
I am not able to return a valid Game from the init function, because I cannot refer to that history array.
If I use a temporary var for the result the pointer will be wrong.

How to solve that? I encounter this problem quite often.

pub const Game = struct
{
    history: [1024]StateInfo,
    pos: Position,

    pub fn init() Game
    {
        return
        .{
            .history = @splat(.empty),
            .pos = .empty, // --> pos.state should be the address of .history[0]
        };
    }
};

pub const Position = struct
{
    state: *StateInfo,
}

I think this is a case of Programming without Pointers. Instead of state being a pointer, have it be an index into the history array. An empty pos would simply be a 0. It would “point” to the history entry that has the state.

True, but the StateInfo contains a prev pointer, which is updated when adding a move.
Chess is mostly a pointer festival…

Maybe it could be rewritten like that without pointers, but the theoretical question remains…

When I need internal pointers, I have the init take a pointer.

const SomeTheoreticalThing = struct {
    buffer: [1024]u8, 
    needs_buffer_slice: ChildThing,

    pub fn init(thing: *SomeTheoreticalThing) void {
        thing.buffer = @splat(0);
        thing.needs_buffer_slice = .{
            .needs_buffer_part = thing.buffer[0..32];
        };
    }
};

pub fn main() !void {
    //  ...
    var thing: SomeTheoreticalThing = undefined;
    thing.init();
    //  ...
}

But then we are starting to get into an X/Y problem.

3 Likes

Was mid writing something like this. :sweat_smile:

Also not directly in this case, but could be handy to declare empty field on the SomeTheoreticalThing and initialize it to that (0.14 style) instead of undefined and then call init() on it.

I used it a bit in my game, where i had few smallish static scenes and components had to reference each other, while having some fields valid before this “linking” happened.

Robert :blush:

1 Like

Yes true… I do something like that as well now.

Could prev be an index too?

1 Like

No. During search the StateInfo’s are in the (recursive) callstack only.

In other cases I use an array for the StateInfo’s(for the one and only global Position)