`offset `

in your code is a little misleading as it normally refers to a byte offset. In your case you are simply calculating the element index in a one-dimensional array. What you are doing (correctly) is to map the elements of a two-dimensional array to a one-dimensional array. And you are doing it by storing the elements of each row in a contiguous range of cells. For example, for an array with two rows and four columns you would store the elements in the following order:C++

R0C0 R0C1 R0C2 R0C3 R1C0 R1C1 R1C2 R1C3

RxCy denoting the element of row x and column y. And that is how you come to the formula of

(Number of columns) * rowIndex + colIndex

You can easily expand that scheme to more dimensions. For example, in a three-dimensional array we might call our dimensions: column, row, plane. And the formula would be:

(Number of rows * number of columns) * planeIndex + (number of columns) * rowIndex + columnIndex

Depending on which dimension is stored contiguous, the formula is a little different. For example, your could decide to store the

*plane*dimension contiguously, then the columns, and outermost the rows. For this storage order the formula would be:

(Number of planes * number of columns) * rowIndex + (number of planes) * columnIndex + planeIndex

Both storage schemes are different. But as long as you use the same scheme for storing and retrieval, everything will work fine. The order in which dimensions are stored has however an influence on how the processor cache will be used and may have an impact on processing time for large numerical computations.