Copy array to array

Probable a very simple question, but I can’t get a solution out of this. I have an array:

var pos:[4]usize;

Later I create a new array:

const npos: []usize=pos[0..pos.len];

Now I want to copy back npos to pos, and thought it might be done with:

@memcpy(pos,npos);

but the compiler doesn’t agree:

type '[4]usize' is not an indexable pointer

Is there a way to copy an array to another array without having to copy it element by element?

This is not a new array.
It is a slice (pointer and length) that points to the pos array.

From @memcpy reference:

dest must be a mutable slice, a mutable pointer to an array, or a mutable many-item pointer. It may have any alignment, and it may have any element type.

(the same for source)

When calling @memcpy npos is acceptable as mutable slice, but pos in neither a slice nor a pointer to an array. It is an array. To get the pointer to the array we can call &pos.

The correct call is: @memcpy(&pos, npos);

But since npos points to pos this just copies the bytes to itself.

1 Like

So what I need to do is:

var npos: [4]usize=undefined;
@memcpy(&npos,&pos);

And later:

@memcpy(&pos,&npos);

Correct?

Correct, if you already have a value in pos and you want to initialize npos with the same value.

Correct, if you want to copy npos to pos.


An example program:

const std = @import("std");

pub fn main() void {
    var pos: [4]usize = .{ 1, 2, 3, 4 };
    var npos: [4]usize = undefined;
    @memcpy(&npos, &pos);
    std.debug.print("npos={any}\n", .{npos});
}

The above example prints npos={ 1, 2, 3, 4 }

2 Likes

Since arrays have value semantics, I believe you can just do

var npos = pos;
8 Likes

That’s right:

const std = @import("std");

pub fn main() void {
    var a = [_]usize{1,2,3,4};
    var b: [4]usize = undefined;

    b = a;
    std.debug.print("{any}\n", .{b});
    for (&b) |*v| {
        v.* += 1;
    }
    a = b;
    std.debug.print("{any}\n", .{a});
}

prints

{ 1, 2, 3, 4 }
{ 2, 3, 4, 5 }
2 Likes