1

I read in C++ book, that "Even though C++ enables us to model multidimensional arrays, the memory where the array is contained is one-dimensional. So the compiler maps the multidimensional array into the memory space, which expands only one direction."

And I thought, if I want to change n-dimension Array to 1-dimension Array(in order of Ascending) why just I call n-d array memory address(which is stored in 1-d format) and just put into new 1-d Array??

(usually I used for statement to change n-d array into 1-d array)

Is it possible?? and if it possible it would be thankful to provide simple example code.

  • Possible duplicate of https://stackoverflow.com/questions/48122708/is-using-2-dimensional-array-as-1-dimensional-array-correct-may-cause-undefined/48122822#48122822 – Galik Apr 14 '18 at 07:58

2 Answers2

1

A pointer to the first item in the array is also a pointer to the complete array considered as a one-dimensional array. The guarantee that the items are stored contiguously in memory comes from the sizeof requirements, that the size of an array of n items is n times the size of the item, also when the item is itself an array.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • And is it language conformant to simply say e.g. `static int arr3d[3][4][5]; int *p = (int *)arr3d; for(int i=0; i<3*4*5; i++) p[i] = i;` ? – Peter - Reinstate Monica Apr 14 '18 at 07:12
  • @PeterA.Schneider: formally not without a lot of supporting argumentation that not everybody will be convinced by, because you have a `reinterpret_cast` in there. That cast is completely unnecessary. You can just do `&arr3d[0][0][0]`. – Cheers and hth. - Alf Apr 14 '18 at 07:16
  • I understand what you are saying. Then for example, if there is Arr2d[2][2] then the address of Arr2d is same as address of Arr2d[0][0] so I should just input the Arr1d[4] by pointer incresement of Arr2d[0][0]. Am I right? – TaeHyeong Kim Apr 14 '18 at 07:17
  • @TaeHyeongKim: I think you're right, when s/should/can/ ;). – Cheers and hth. - Alf Apr 14 '18 at 07:18
  • @Alf well, I'm confident about the cast. It also bothers me if people dereference only in order to take the address ;-) (it's equivalent to writing `p = &(***arr3d);`) -- if anything I'd write `p = arr3d[0][0];`... – Peter - Reinstate Monica Apr 14 '18 at 07:18
1

Yes, it is possible to convert an n-dimensional array to 1-d array.

Let me show by taking an example of 2-d array:

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        b[i * n + j] = a[i][j];
    }
}
Abhishek Keshri
  • 3,074
  • 14
  • 31