How to store constant pointers in a buffer at compile time?

I tested the following code, and they can all assign values to variables at compile time.


test "comptime" {
    const num: usize = 0;
    comptime {
        var ptr: *const anyopaque = undefined;
        ptr = #
    }
    comptime {
        var array: [10]*const anyopaque = undefined;
        for (&array) |*item| {
            item.* = #
        }
    }
    comptime {
        var buf: [64]u8 = undefined;
        const slice: []align(1) usize = std.mem.bytesAsSlice(usize, &buf);
        slice[0] = 100;
    }
    comptime {
        var buf: [64]u8 = undefined;
        const slice: []align(1) *const anyopaque = std.mem.bytesAsSlice(*const anyopaque, &buf);
        slice[0] = @ptrFromInt(100);
    }
}

But when I tried another piece of code, it resulted in an error.

test "comptime_error" {
    comptime {
        const num1: usize = 0;
        var buf: [64]u8 = undefined;
        const slice: []align(1) *const anyopaque = (std.mem.bytesAsSlice(*const anyopaque, &buf));
        slice[0] = &num1;
    }
}
 error: value stored in comptime field does not match the default value of the field
        slice[0] = &num1;
        ~~~~~~~~~^~~~~~~

Why does this happen? If the previous code snippets work, why does this one result in an error?

Can this issue be resolved?

I was unable to reproduce this error due to encountering a segment fault. :joy:

const std = @import("std");
test "comptime_error" {
    comptime {
        const num1: usize = 0;
        var buf: [64]u8 = undefined;
        const slice: []align(1) *const anyopaque = (std.mem.bytesAsSlice(*const anyopaque, &buf));
        slice[0] = &num1;
    }
}

I tested two versions of zig on the Debian operating system, including master and 0.15.2, and both encountered segmentation faults… On what operating system and version did OP get a compilation error?

npc1054657282@localhost:~/projects/zig-tests$ /home/npc1054657282/.vscode-server/data/User/globalStorage/ziglang.vscode-zig/zig/x86_64-linux-0.16.0-dev.2905+5d71e3051/zig test test.zig
Segmentation faultg
npc1054657282@localhost:~/projects/zig-tests$ /home/npc1054657282/.vscode-server/data/User/globalStorage/ziglang.vscode-zig/zig/x86_64-linux-0.15.2/zig test test.zig
Segmentation fault

Thanks for your response. Here are my device details

> sysctl -a | grep "cpu.brand_string"
machdep.cpu.brand_string: Apple M1 Pro
> uname -a
Darwin xxx.local 24.6.0 Darwin Kernel Version 24.6.0: Wed Oct 15 21:12:06 PDT 2025; root:xnu-11417.140.69.703.14~1/RELEASE_ARM64_T6000 arm64

That looks like a compiler bug to me. Godbolt simply segfaults https://zig.godbolt.org/z/8483sa6qa so you are probably hitting UB which explains why the error for you is so weird. The code itself being valid or not, idk, seems very cursed.