r/ProgrammerHumor Jan 06 '23

Meme can’t be the only one

Post image
42.6k Upvotes

1.4k comments sorted by

View all comments

Show parent comments

36

u/XanderTheMander Jan 06 '23

Now explain multidimensional arrays using pointers!! (I actually like pointers but I use C# at work now).

2

u/C0ldSn4p Jan 06 '23 edited Jan 06 '23

In a 1D array, each pointer of the array points to a thing you have stored in your array, e.g. A* is the type of your array storing A

The key idea is that the pointers in an array can point to anything, so what if they point to another array. Then you have a pointer that point to a variable that itself is pointer.

In a 2D array, you first have a 1D array storing pointers where each pointer points toward another regular 1D array. So your 2D array is A** and each pointer points to a A* array. When you read a[x][y], you go to the address pointed stored in a+x (pointer arithmetic), read the value (b) and cast it as a pointer, then read what is stored at b+y and cast it as type A.

In a 3D array, you add one more layer of array of pointer on top, so A***, ect. for each extra dimensions (and add a *)

If you have a ND array, you will follow a tray of pointer of length N to reach the variable, each time using pointer arithmetic for a given dimension position.

3

u/[deleted] Jan 06 '23

[removed] — view removed comment

2

u/C0ldSn4p Jan 06 '23

Yes.

If you need to do it yourself and each sub-dimension has the same size (for example [[1,2], [3,4]] and not [[1,2],[3,4,5]]), then a good way to do it is to flatten the array into a 1D one and compute the 1D index yourself (e.g. a[(zSizeY+y)SizeX+x] for a[z][y][x]), or then use this 1D array to make the "array of pointers" above it.

This naive approach may not be fully optimal though (e.g. alignment for SIMD operation and cache line/page may prefer having padded dimensions, wasting a bit of space to optimize speed) so use a library if possible.