2

Im trying to pass a 3 Dimensional array to a function. I got this decleration of the array

char cube[N][N][N];

It's size (N) is a constant.
I want to pass it to a function so I can work on the array in the function and change it without copying the entire array each call..

I actually want to pass a pointer to the beginning of the array and be able to put some info to the array in the function.

Thanks for the help.

Nadav Peled
  • 951
  • 1
  • 13
  • 19
  • 1
    That is precisely what's going to happen automatically: you cannot force C to pass an individual array by value even if you wanted to - it will decay to a pointer. If you wanted to pass an array by value, you'd be forced to wrap an array in a `struct`, and pass that `struct` instead. – Sergey Kalinichenko Jan 03 '14 at 21:14

3 Answers3

6

Well, the simplest is to just declare the parameter as char cube[N][N][N]; or char cube[][N][N]; in your function, and the array will be passed by pointer (yes, it's counter-intuitive, but it really is how it works.

Medinoc
  • 6,577
  • 20
  • 42
  • Wow.. that was really counter-intuitive.. I was sure it'll copy the array by value :| – Nadav Peled Jan 03 '14 at 21:16
  • The counter-intuitivity is why you should use the second writing, which hints a little more about what actually happens. Alternately, you could also write it `char (*cube)[N][N]`, since that's how it's actually passed under the hood: This obscure syntax means "pointer to 2D array" (since a 3D array is just an array of 2D ones, we're actually passing a pointer to its first element), think of it as `char[N][N]* cube` only with a more bizarre syntax. – Medinoc Jan 03 '14 at 21:21
1

Declare the parameter for your function as char cube[][N][N] (you can omit the length of the first dimension). You can also declare it as char (*cube)[N][N] (in fact compiler would parse char cube[][N][N] as char (*cube)[N][N]).

I actually want to pass a pointer to the beginning of the array and be able to put some info to the array in the function.

Now your function is expecting an argument of type char (*)[N][N]), i.e, pointer to a 2D array of chars. Either you pass cube (decays to the first element, i.e, row of the 3D array) or &cube[0] (pointer to the first row of the 3D array cube) as an argument to your function. Now any modification to this passed array (pointer to array) in the function would be reflected to the original array.

Suggested reading: Here is a good answer regarding 2D arrays. It will help somehow.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
0

I would like to add to the previous answers .

you can also , if you allocate that array dynamically ,pass the triple pointer char ***cube , but only if you allocate it dynamically

Farouq Jouti
  • 1,657
  • 9
  • 15