Imagine dropping a 2D array into a 1D array:
int arr2D[2][3]; int arr1D[2 * 3]; // # of rows * # of columns // access element [1][2] of 2D array, ie, the last element int elem2D = arr2D[1][2]; // access element [1][2] of 1D array, ie, the last element int elem1D = arr1D[1 * 3 + 2]; // ========================================================= lets visualize the array access: arr2D => x/y 0 1 2 0 [N][N][N] +1 on x > 1 [N][N][N] +2 on y ---------- ^ y_len => ^-------^ 3 elements so the access happens with x * y_len + y 1 * 3 + 2 now for the 1D array we want the second row, so we go with 1 * 3 (0-based access, y_len = 3) and then we want the 3rd element, so + 2 (again, 0-based access) arr1D => x 0 1 2 [N][N][N] 3 4 5 1 * 3 = 3 > [N][N][N] + 2 = 5 ---- ^
I hope I did not make it too complicated (although I thought ...). :)
source share