Variable Size Multi Dimensional Array Casting

Hi all.

This is my first post so before I start begging for help let me first say that I am very grateful to the people who contribute and created this site. It has been invaluable to me for quick and easy reference. So thank you, hugely.

Now to my "problem". I am working with a game engine library, and for the most part everything is great. I just have a small issue that I would ideally like to fix. The library does many things, one of which is supply Game Map data.

int s_x, int s_y;
char* mapData=(char*)MapData(s_x,s_y);

s_x and s_y are output vars which receive the dimensions of the 2D map (W x H), each map element is comprised of 8 bytes, s_x of these form 1 row and s_y rows form the entire data block.

At the moment I can access byte (n) of the element at a particular row (y) and column (x) like this:
mapData[ (s_x*y*8) + (x*8) + n ]

What would be very useful to me is if I could access an element like this:
mapData[y][x][n]
So far I have not been able to find any information on casting the pointer to a multidimsional array type. I can do it if the map size is always the same using a typedef but I cannot work out or find out how to cast to variable sizes or if it's even possible.

Many thanks for any help.
Marc.



Last edited on
It is possible to build such structure which would work as you want it. If you wanted a 2d array, you would first need an array of pointers to the beginning of each row. If you took a pointer to that array, you could apply [] twice. With a 3d array, of course, you would need another layer of arrays (should I explain more?). However this requires some work, gives no benefit to the resulting application and might be hard to debug. It would be better to simply write
1
2
3
char get_tile(int x, int y, int n) {
   return mapData[ (s_x*y*8) + (x*8) + n ];
}
Last edited on
Thanks for the reply. The function you posted is pretty much how am am doing things already. I was concerned that having 3 multiplications in the element retrieval would be less efficient than a 3d array. Map elements are used frequently in the application. Since the elements are 8 bytes long i can use a left 3 bit shift instead of *8 which might reduce overhead, but I was hoping a 3d array situation would be a lot faster.

I could reduce complexity by using a 2d array of UINT64 types i guess.
Last edited on
The compiler should optimize *8 to <<3 for you. Also, each [] result in a pointer being dereferenced and memory being read. I can't say how that compares to a multiplication. I suppose that depends on many things.
But that doesn't matter. This is a trivial procedure, it takes negligible amount of time. I don't think this is a place where you should look for ways to optimize.
Topic archived. No new replies allowed.