0

In logic, for a 3d array, we need to access the outer array first and work our way inside inside each dimension and access th array's element. Since, physical memory store arrays as a block of memory irrespective of its dimensions, can we directly access using it address as there are ways to get a memory location?

If a multi dimensional array is stored in physical memory as a 1d array, can we access the array's deeper elements directly if we know the memory address?

Kiran Cyrus Ken
  • 379
  • 1
  • 3
  • 17
  • it is c language – Kiran Cyrus Ken Jul 13 '20 at 00:59
  • How is the array defined? – user2864740 Jul 13 '20 at 01:01
  • 1
    If it s a true 3D array then yes, all you need is the start address and array dimensions to be able to access all elements in the array. In fact, the array `[]` notation is just convenience syntax and translates to the same memory address calculations. – kaylum Jul 13 '20 at 01:08
  • Say you have an `array[x][y][z]` where `x`, `y`, `z` are the dimensions. To work from the outer 2D arrays in, you can do `int i = 0, j = x-1;` and then `while (i < j) { /* work with array[j][y][z] and array[i][y][z], then i++, j-- */ }` You add a special case of `i == j` and only process the final 2D array once if `x` is odd. – David C. Rankin Jul 13 '20 at 01:13

1 Answers1

0

You can certainly see a 3D array int arr[a][b][c] as a "flattened" 1D array int flattened[a * b * c] and access its elements accordingly.

int arr[3][4][5];

int * flattened = &arr[0][0][0];

Element arr[i][j][k] would correspond to flattened[b * c * i + c * j + k].

It is even well-defined behavior since array elements are guaranteed to be contiguous in memory.

tlongeri
  • 122
  • 1
  • 7