-1

I'm struggling to pass a C99 static 3D array of variable length to a function. I know this has been asked here on SO before, but I tried every solution I found so far, none of them worked. I have a following code:

int N;

int foo( ? ){

  // do stuff 

}

int main(){

   cin >> N;
   int arr[N][N][N];

   foo(arr);

return 0;
}

The question is what to put instead of '?'. Among other things I tried creating a pointer to this 3D array and passing the pointer according to the answer here but that also would compile.

abhi
  • 1,760
  • 1
  • 24
  • 40
V.Mach
  • 1
  • 1
  • If you make your array size depend on anything that is calculated at runtime that will be undefined behavior in C++ (because you tagged this as C++). If this *isn't* C++, please don't tag it as such. – hlt May 19 '18 at 22:53
  • Why are you right-shifting `cin`? (which is an undeclared variable anyway) – M.M May 20 '18 at 04:47

1 Answers1

0

C++ does not have variable-style arrays. What you can do is cast the address of the array to a pointer, and pass the dimensions, or even cast to a pointer to an array of the same size but different shape, then dereference that pointer.

One C++ technique you can use to sugar this, if you are selecting between a finite number of possible shapes, is to declare a template< size_t L, size_t M, size_t N> int foo( int arr[L][M][N]). Another would be a multidimensional array class that wraps your array and its dimensions. You can then construct an object, which aliases rather than copies the array, that you can index as arr(i, j, k).

Davislor
  • 14,674
  • 2
  • 34
  • 49