I have the following code for 2D dimensional arrays being flattened as 1D C-style arrays:
#include <iostream>
int main()
{
int width = 4, height = 10;
int arr[width * height];
for (int i = 0, k = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
arr[i * width + j] = k++;
}
}
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
int* ptr = &arr[0] + height * i; //perfect also works with &arr[0] + width * i;
std::cout<<ptr[j]<<" ";
}
}
}
It prints: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
as demonstrated here: http://ideone.com/gcgocu
The array does NOT have to be a square (4x4) and the above still works.
Knowing that the above works, I made a class out of it and I defined an index operator as:
int* operator [](const int index) {return ptr + width * index;}
Such that I can do: Instance[i][j]
and it works just fine.
Now I'm trying to do the same thing with a 3D array so I did:
#include <iostream>
int main()
{
int width = 4, height = 4, depth = 4;
int arr[width * height * depth];
for (int i = 0, l = 0; i < depth; ++i)
{
for (int j = 0; j < height; ++j)
{
for (int k = 0; k < width; ++k)
{
arr[k + width * (j + depth * i)] = l++; //works just fine. perfect.
}
}
}
//Fails below.. Run-time access violation error.
for (int i = 0; i < depth; ++i)
{
for (int j = 0; j < height; ++j)
{
for (int k = 0; k < width; ++k)
{
int** ptr = reinterpret_cast<int**>(&arr[0] + width * i); //this can't be right.
std::cout<<ptr[j][k]; //this line should stay the same.
}
}
}
return 0;
}
It fails as demonstrated here: http://ideone.com/yqY2oK
How can I do the same thing for a 3D array? I tried asking stackoverflow and got a simple answer:
Never do this. In fact by doing this you are cheating your compiler. Old saying: Cheating is not a problem but if it being caught, then it is a problem. Sometimes you may get some unexpected result.
Answers like that one just doesn't help me. It's vague and just makes me want to get it done even more if it is possible at all. I was told not to do it for n-dimensional arrays starting from 2. So 2D, 3D, 4D, etc.. It has never failed me for 2D arrays so I want to know why I shouldn't do it and how can I do it for 3D arrays.
Any ideas??