Roy Roy - 11 days ago 6
C Question

Correct Subscript Ordering for Two Dimensional Arrays

I am talking about a zero-indexed matrix of integers denoted by a pointer to pointer, i.e.

int **mat;


Then what is the correct way to represent the mat[m][n] element? Is it

*(*(mat+m)+n)


or is it

*(*(mat+n)+m)


Also, visually speaking, between m and n, which one is the row index or which one is the column index? Or do terms like row and column make any sense here? I am sure I have some conceptual gap here, and some help will be great.

Answer

The expression

mat[m][n]

is parsed as

(mat[m])[n]

which is equivalent to

(*(mat + m))[n]

which is in turn equivalent to

*(*(mat + m) + n)

so your initial guess is correct.

As for which of these mean rows and which of these mean columns - in some sense, this is up to you to decide. You're the one creating the array and you can assign it any semantics that you'd like.

On the other hand, if you create a 2D array like this:

int mat[A][B];

then in memory this will be laid out as

[0, 0][0, 1][0, 2]...[0, B-1][1, 0][1, 1][1, 2]... ... [A-1][B-1]

Because of locality of reference, if you read across this in the order shown above (do all of mat[0], then all of mat[1], etc.) than it is to iterate in the reverse order (do mat[0][0], then mat[1][0], then mat[2][0], etc.). In that sense, it's common to treat 2D arrays as having the first component select a row and the second select a column, since that more naturally aligns with how the memory is laid out.

Comments