Hello,
I'm currently translating some C code to Zig, as an exercise.
I wanted to translate these lines:
uint32_t* pixels = malloc(width * height * sizeof(pixels[0]));
float* depth = malloc(width * height * sizeof(depth[0]));
At first, I thought that I could do this:
var g_pixels: ?*u32 = null;
var g_depth: ?*f32 = null;
and use the std.heap.FixedBufferAllocator.
But it turns out that std.heap.FixedBufferAllocator can only allocate buffer of type u8. So I didn't understood how to convert that to u32 and f32.
As I've been tinkering around, I've ended up with the following monstrosity:
const k_screen_width: i32 = 320;
const k_screen_height: i32 = 200;
const k_screen_pixels: i32 = k_screen_width * k_screen_height;
var g_pixels: []u8 = undefined;
var g_depth: []u8 = undefined;
var g_pixels_fba: std.heap.FixedBufferAllocator = undefined;
var g_depth_fba: std.heap.FixedBufferAllocator = undefined;
...
fn game_memory_init() void {
g_pixels_fba = std.heap.FixedBufferAllocator.init(g_pixels);
const pixels_allocator = g_pixels_fba.allocator();
const pixels_memory: error{OutOfMemory} = try pixels_allocator.alloc(u32, k_screen_pixels);
try pixels_memory.len == k_screen_pixels;
try @TypeOf(pixels_memory) == []u32;
...
}
Which, of course, doesn't work, because it simply shows that I don't understand what I'm doing.
As I struggle with the new concepts of allocation, and with the intricaties of the Zig syntax, I would like to know what is the Zig way to convert this C code:
uint32_t* pixels = malloc(width * height * sizeof(pixels[0]));
float* depth = malloc(width * height * sizeof(depth[0]));
Thank you very much for your attention.