passing a 3D array with different size to a function

Started by
4 comments, last by King Mir 9 years, 6 months ago

I have:


char cubesA[100][100][100];
char cubesB[30][30][30];

how can I pass them as a parameter to access them using the three square brackets[][][] inside a fuction?

this:

void function( char cubes[][a][b] )
{
     //---
}
doesn't works here because the "a" and "b" can be 30 or 100
is there no way?
Advertisement

Hi.

Try function(char ***ar, DWORD size1, DWORD size2, DWORD size3)

how can I pass them as a parameter to access them using the three square brackets[][][] inside a fuction?


a[10][20] and a[40][50] are fundamentally different things. Remember that array notation is (roughly speaking) just a fancy facade for a pointer. Accessing a multi-dimensional array is the same as accessing a pointer with a little arithmetic. The compiler has to know what arithmetic to use, though. a[] is alright since the compiler can figure it out (it's just a+x) but a[][] is not alright (since the compiler needs to use a+N*y+x but has no idea what N is).

If you want to pass around multidimensional arrays you're going to have to provide more information to the implementation of your function. This can be done manually in C by passing in a pointer and the dimension information as distinct parameters and just doing all the work yourself. It can be done statically in C++ using templates letting the compiler do all the heavy work.

template <typename T, size_t N, size_t M>
void foo(T(&cubes)[N][M]) {
  // you can access `cubes` like you'd expect, sizeof works, etc.
};

int main() {
  char test[10][20];
  foo(test); // deduces to foo<char, 10, 20>(test);
}

Sean Middleditch – Game Systems Engineer – Join my team!

You also might consider make a cube struct and then define one or more std::vector's with them. So you can simply pass a pointer to the vector or the vector itself if you like

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

Hi.
Try function(char ***ar, DWORD size1, DWORD size2, DWORD size3)


Nope nope. This is C++.

That says a pointer to a pointer to a pointer to an object.

In C and C++ multidimensional arrays are laid out continuously and accessed based on stride. The compiler is smart enough to use those sizes and do the stride for you.

In this case, you would need the parameters for sizes, but just pass a pointer. Then add the stride. That is ((y*xstride)+x) or ((z*xstride*ystride)+(y*xstride)+x) or more depending on your dimensionality.

What are you trying to do?

Often times when your program calls for a multidimensional array it's better to put that array in an object that better restricts legal operations on the array. So instead of passing around an array, you would pass around an object that internally used an array in it's implementation.

This topic is closed to new replies.

Advertisement