Zig: Multidimensional Arrays

Created on 14 Jul 2019  路  5Comments  路  Source: ziglang/zig

I looked through the documentation etc. but I can't seem to find any reference on how to define and initialise multidimensional arrays (e.g. arrays of strings). Is this supported and, if so, how would I do this?

docs

Most helpful comment

[]T is a slice, not an array. A slice is a pointer and a length. A multi dimensional array looks like [N][M]T.

I'll leave this issue open to add a multidimensional array example to the docs.

All 5 comments

Just keep reading each [] as "array of" and you already have it.

var arStr: [2][]const u8 = [_][]const u8{"Hello", "There"};

for(arStr) |str| {
    std.debug.warn("{}\n", str);
}
There

The initialization syntax ought to get somewhat better when we get this merged in.

Apologies if this isn't the correct place, but how would you pass this to a C function that takes the equivalent multi dimensional C-array?

For example:

var nameCount: usize = 4; //for example
var names: [*c][*c]const u8 = undefined;   
c_function(nameCount, &names);  // a c function that fills a const char** with data

I'm honestly not sure if there's a better place either.

This seems to compile at least:

// I believe the C function would be translated to something like this by zig
pub extern fn c_function(count: usize, data: [*c][*c]const u8) void;
...
var nameCount: usize = 4; //for example
var names: [4][]const u8 = undefined; 
c_function(nameCount, @ptrCast([*c][*c]const u8, &names));

If I'm understanding the casts correctly here, &names gets implicitly cast from *[N]T to [*]T, which is then allowed to be cast to a C pointer.

Ah, I must have missed that in the casts section. Thank you :)

[]T is a slice, not an array. A slice is a pointer and a length. A multi dimensional array looks like [N][M]T.

I'll leave this issue open to add a multidimensional array example to the docs.

Was this page helpful?
0 / 5 - 0 ratings