Search code examples
zig

How to create an array variable and allocate it later in Zig?


I'm trying to allocate some number of bytes to an uninitialized var of type u8 in a different scope, the array can not be const. The compiler keeps complaining about unmatching type:

error: expected type '*const[0:0]u8', found '[]u8' 

What am I doing wrong, how can we do this?

  1. Create an empty array, here one of type u8 (a string)

    var my_array = "";
    
  2. In another scope, allocate it to match some parameter

    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    
    if (true) {
      my_array = try allocator.alloc(u8, 4);
      defer allocator.free(my_array);
      std.mem.copyForwards(u8, my_array, "okok");
    }
    
  3. When building you get a type error:

    error: expected type '*const[0:0]u8', found '[]u8' 
    

However, it works when calling the allocator.alloc on a const array. But then I can not access it in the greater scope.

const my_array = try allocator.alloc(u8, 4);

Solution

  • The type of "" is *const[0:0]u8 (which is just a pointer) but allocator.alloc(u8, 4) returns []u8 (which consists of a pointer and a length), so you get a type mismatch.

    To create a variable of type []u8 and leave it uninitialized, you can use

    var my_array: []u8 = undefined;
    

    This means you must not access my_array at all (e.g. use my_array.len) until you have assigned a valid slice value to it.

    If you cannot guarantee this, you can initialize it as a valid, but empty, slice like this:

    var my_array: []u8 = &.{};