Ok, I have a some array A[4][4], and another A[16], which are both just different representations of each other. Now, I am given an elements position on the 2D array, but I have to access it from the 1D array. IE, if I'm told to access the element A[2][0] in my 1D array, how would I do that?
2 Answers
This depends on your programming language and choice of array type. Depending on your language, arrays are either stored in row-major order or column-major order:
Edit: Java does not have multidimensional arrays, as per the documentation: In Java, a multi-dimensional array is structured an array of arrays, i.e. an array whose elements are references to array objects. This means that each row can be of different length and therefore the storage format is neither row-major nor column-major.
Row-major order is used in C/C++, PL/I, Python, Speakeasy and others. Column-major order is used in Fortran, MATLAB, GNU Octave, R, Julia, Rasdaman, and Scilab.
In some languages, you can also choose the order (e.g. MATLAB)
For row-major order, A[2][0]
would be at A[2*4+0]
(where 4 is the size of one row):
offset = row*NUMCOLS + column
For column-major order, A[2][0]
would be at A[0*4+2]
(where 4 is the size of one column):
offset = row + column*NUMROWS
It really depends on your programming language!

- 2,991
- 1
- 23
- 34
-
You cannot do this in Java, see updated answer above. – jmiserez Oct 19 '13 at 01:41
-
In my opinion calling memory layout "row-major" or "column-major" [will lead to confusion](http://stackoverflow.com/questions/17717600/confusion-between-c-and-opengl-matrix-order-row-major-vs-column-major/17718408#17718408), because data stored in array's "row" doesn't necessarily represent row. – SigTerm Oct 19 '13 at 02:00
In this simple example, A[2][0]
maps to A[8]
since you are requesting the first element in the third group of four. Similarly, A[0][2]
maps to A[2]
since you are requesting the third element of the first group of four. In general (A[i][j]
) you are requesting the (i*4+j)-th element of A
.
In the even more general case, you are requesting the (i*width+j)-th element.

- 8,154
- 4
- 36
- 49