Logo

Programming-Idioms

Create the new 2-dimensional array y containing a copy of the elements of the 2-dimensional array x.

x and y must not share memory. Subsequent modifications of y must not affect x.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
integer, allocatable, dimension(:,:) :: y

y = x
buf := make([]T, m*n)
y = make([][]T, m)
for i := range y {
	y[i] = buf[:n:n]
	buf = buf[n:]
	copy(y[i], x[i])
}
func clone2D[M ~[][]T, T any](in M) (out M) {
	if len(in) == 0 {
		return nil
	}

	m, n := len(in), len(in[0])

	buf := make([]T, m*n)

	out = make(M, m)
	for i := range out {
		out[i] = buf[:n:n]
		buf = buf[n:]
		copy(out[i], in[i])
	}
	return out
}
int[][] y = new int[x.length][];
for(int index1 = 0; index1 < x.length; index1++) {
	y[index1] = new int[x[index1].length];
	for(int index2 = 0; index2 < x[index1].length; index2++) {
		y[index1][index2] = x[index1][index2];
	}
}
y := x;
y := copy(x, Low(x), Length(x));
use Storable qw(dclone);
$y = dclone($x);
import copy
y = copy.deepcopy(x)
y = Marshal.load(Marshal.dump(x))
let y = x.clone();