1

I know how pointers work for a 1D and 2D array, but I'm trying to figure it out for a 3D array.

For a 1D array:

V[i] ==> *(V+i)

for a 2D array with C columns

M[i][j] ==> *(M+(C*i+j))

What would be the pointer arithmetic for a 3D array?

4 Answers 4

3

Rewriting the subscription using pointer syntax then expanding the pointer arithmetic gives:

M[i][j][k] = *(*(*(M + i) + j) + k) = *(&M[0][0][0] + x * y * i + y * j + k)

where x, y and z (the latter one unused) are the dimensions of the array.

Sign up to request clarification or add additional context in comments.

Comments

3
M[i][j] ==> *(M+(C*i+j))

wrong. It is

M[i][j] ==> *(*(M+i)+j)

for 3D

M[i][j][k] ==>  *(*(*(M+i)+j)+k)

4 Comments

you're doing triple dereferencing here?
Isn't this for an array of pointers, not an n-dimensional array?
@yngum No. 2D arrays aren't arrays of pointers. 3D arrays aren't arrays of arrays of pointers.
It works because of the way arrays decay to pointers in various contexts in C. But it's not very helpful for understanding how multiple dimensions map to row-major indexing in memory, which seems to be what the OP is looking for.
2

If the 3D array has C columns and R rows, each slice is C*R elements.

M[i][j][k] = *(M + C*R*i + C*j + k)

Comments

0

for a matrix M[X][Y][Z]

M[i][j][k] = *(M+(Y*Z*i+Z*j+k))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.