How to resize multidimensional (2D) array in C#? -
i tried following returns screwed array.
t[,] resizearray<t>(t[,] original, int rows, int cols) { var newarray = new t[rows,cols]; array.copy(original, newarray, original.length); return newarray; }
most methods in array class work one-dimensional arrays, have perform copy manually:
t[,] resizearray<t>(t[,] original, int rows, int cols) { var newarray = new t[rows,cols]; int minrows = math.min(rows, original.getlength(0)); int mincols = math.min(cols, original.getlength(1)); for(int = 0; < minrows; i++) for(int j = 0; j < mincols; j++) newarray[i, j] = original[i, j]; return newarray; }
to understand why doesn't work array.copy
, need consider layout of multidimensional array in memory. array items not really stored bidimensional array, they're stored contiguously, row after row. array:
{ { 1, 2, 3 }, { 4, 5, 6 } }
is arranged in memory that: { 1, 2, 3, 4, 5, 6 }
now, assume want add 1 more row , 1 more column, array looks this:
{ { 1, 2, 3, 0 }, { 4, 5, 6, 0 }, { 0, 0, 0, 0 } }
the layout in memory follows: { 1, 2, 3, 0, 4, 5, 6, 0, 0, 0, 0, 0 }
but array.copy
treats arrays one-dimensional. msdn says:
when copying between multidimensional arrays, array behaves long one-dimensional array, rows (or columns) conceptually laid end end
so when try copy original array new one, copies 1 memory location other, gives, in one-dimensional representation:
{ 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }
.
if convert two-dimensional representation, following:
{ { 1, 2, 3, 4 }, { 5, 6, 0, 0 }, { 0, 0, 0, 0 } }
this why you're getting screwed array... note work property if changed number of rows, not number of columns.
Comments
Post a Comment